[Go to site: main page, start]

0% found this document useful (0 votes)
11 views51 pages

JavaScript Basics: Variables & Functions

This document provides an overview of JavaScript basics, including variables, functions, and the Document Object Model (DOM). It covers key concepts such as variable declaration, data types, function syntax, and the importance of the DOM for dynamic web content. Additionally, it highlights best practices for coding in JavaScript, including naming conventions and the use of modern keywords like let and const.

Uploaded by

farukiamen5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views51 pages

JavaScript Basics: Variables & Functions

This document provides an overview of JavaScript basics, including variables, functions, and the Document Object Model (DOM). It covers key concepts such as variable declaration, data types, function syntax, and the importance of the DOM for dynamic web content. Additionally, it highlights best practices for coding in JavaScript, including naming conventions and the use of modern keywords like let and const.

Uploaded by

farukiamen5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Javascript Basics

 JavaScript variables
 Javascript functions
 Javascript DOM

-Chetashri Sachin Bhusari


lecturer, Vidyalankar Polytechnic
JavaScript

 JavaScript is the programming language of the web.


 It can calculate, manipulate and validate data
 It can update and change both HTML and CSS.
The <script> Tag

 In HTML, JavaScript code is inserted


between <script> and </script> tags.
 Example
<script>
[Link]("demo").innerHTML = "My First
JavaScript";
</script>
JavaScript Keywords

 JavaScript keywords are used to


defines actions to be performed.
 The let and const keywords create
variables:
 Example
let x = 5;
const fname = "John";
Single Line Comments
 Single line comments start with //.
 Any text between // and the end of the line will be ignored by
JavaScript (will not be executed).
 This example uses a single-line comment before each code
line:
 Example
 // Change heading:
[Link]("myH").innerHTML = "My First Page";
// Change paragraph:
[Link]("myP").innerHTML = "My first
paragraph.";
 This example uses a single line comment at the end of each
line to explain the code:
 Example
 let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
Multi-line Comments
 Multi-line comments start with /* and end with */.
 Any text between /* and */ will be ignored by JavaScript.
 This example uses a multi-line comment (a comment
block) to explain the code:
 Example
 /* The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
 [Link]("myH").innerHTML = "My First
Page";
[Link]("myP").innerHTML = "My first
paragraph.";
Semicolons

 Semicolons separate JavaScript statements.


 Add a semicolon at the end of each executable
statement:
 Examples
 let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
JavaScript
Variables
JavaScript Variables

 Variables are containers for storing data


values.
 Variables must be identified with unique
names.
 JavaScript statements are composed of:
Values, Operators, Expressions, Keywords
and Comments.
Introduction to Variables
 Variables store data values
 Declared using var, let, or const
 Case-sensitive naming
 Follow identifier rules
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter, a $ sign or an underscore (_).
 Names are case sensitive (X is different from x).
 Reserved words (JavaScript keywords) cannot be used as names.
Variable Keywords
 var: Function-scoped (older)
 let: Block-scoped (modern)
 const: Block-scoped, constant
 Variables = Data Containers
 JavaScript variables are containers for data.
 Variables are labels for data values.
 Variables are containers for storing data.
 JavaScript variables can be declared in 4 ways:
 Modern JavaScript
 Using let
 Using const
Examples

 var x = 10;
 let y = 20;
 const z = 30;
 From the examples you can guess:
 x contains (or stores) the value 10
 y contains (or stores) the value 20
 z contains (or stores) the value 30
Examples of Good Naming

 let userName = "Alex";


 const maxUsers = 100;
 let isLoggedIn = false;
Rules & Best Practices

 Use meaningful names


 Prefer let/const over var
 Use const for fixed values

 Note
 Numbers are not allowed as the first character in
names.
 This way JavaScript can easily distinguish identifiers
from numbers.
JavaScript Underscore (_)

 JavaScript treats underscore as a letter.


 Identifiers containing _ are valid variable names:
 Example
 let _lastName = "Johnson";
let _x = 2;
let _100 = 5;


Declaring JavaScript Variables
 Creating a variable in JavaScript is called declaring a variable.
 You declare a JavaScript variable with the let keyword or
the const keyword.
 Declaring a Variable Using let
 let carName;
 After the declaration, the variable has no value (technically it
is undefined).
 To assign a value to the variable, use the equal sign:
 carName = "Volvo";
 Most often you will assign a value to the variable when you
declare it:
 Example
 Create a variable called carName and assign the value "Volvo" to
it:
 let carName = "Volvo";
Declaring a Variable
Automatically

 Undeclared variables are automatically declared when


first used:
 Example
 x = 5;
y = 6;
z = x + y;
When to Use var, let, or const?

 Always declare variables


 Always use const if the value should not be changed
 Always use const if the type should not be changed
(Arrays and Objects)
 Only use let if you cannot use const
 Never use var if you can use let or const.
Declaring a Variable Using const

 Always use const if the value should not be changed


 const carName = "Volvo";
 A Mixed Example
 const price1 = 5;
const price2 = 6;
let total = price1 + price2;
JavaScript Dollar Sign $

 JavaScript also treats a dollar sign as a letter.


 Identifiers containing $ are valid variable names:
 Example
 let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;

 Using the $ is not very common in JavaScript, but


professional programmers often use it as an alias for the
main function in JavaScript libraries.
Reassignment

 let: reassignment allowed


 const: reassignment not allowed
 Objects declared with const can still change properties
Data Types in JavaScript

 Number
 String
 Boolean
 Object
 Undefined
 Null
 Symbol
 BigInt
 // Strings
let color = "Yellow";
let lastName = "Johnson";

// Number
let length = 16;
let weight = 7.5;

// BigInt
let x = 1234567890123456789012345n;
let y = BigInt(1234567890123456789012345)

// Boolean
let x = true;
let y = false;

// Object
const person = {firstName:"John", lastName:"Doe"};

// Array object
const cars = ["Saab", "Volvo", "BMW"];

// Date object
const date = new Date("2022-03-25");

// Undefined
let x;
let y;

// Null
let x = null;
let y = null;

// Symbol
const x = Symbol();
const y = Symbol();
Good Coding Practices

 Use const by default


 Use let only when reassignment is needed
 Avoid var
 Use camelCase naming
 Keep variables close to usage
JavaScript Functions
 Functions are fundamental building blocks in all programming.
 Functions are reusable block of code designed to perform a
particular task.
 Functions are executed when they are "called" or "invoked".
 Example
 Function to compute the product of two numbers:
function myFunction(p1, p2 )
{
return p1 * p2;
}
Why Functions?
 Functions enable better code organization and
efficiency.
 With functions you can reuse code.
 You can write code that can be used many times.
 You can use the same code with different arguments, to
produce different results.
JavaScript Function Syntax
 function name( p1, p2, ... )
 {
// code to be executed
}
 Functions are defined with the function keyword:
 followed by the function name
 followed by parentheses ( )
 followed by brackets { }
 The function name follows the naming rules for variables.
 Optional parameters are listed inside parentheses: ( p1, p2, ... )
 Code to be executed is listed inside curly brackets: { }
 Functions can return an optional value back to the caller.
JavaScript Function Parameters
 A JavaScript function does not perform any checking on parameter
values (arguments).
 function functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}
 Function parameters are the names listed in the function
definition.
 Function arguments are the real values passed to (and received by)
the function.
Parameter Rules

 JavaScript function definitions do not specify data types


for parameters.
 JavaScript functions do not perform type checking on
the passed arguments.
 JavaScript functions do not check the number of
arguments received.
Default Parameters
 If a function is called with missing arguments (less than
declared), the missing values are set to undefined.
Sometimes this is acceptable, but sometimes it is better to
assign a default value to the parameter:
Example
function myFunction(x, y)
{
if (y === undefined)
{
y=2;
}
}
Default Parameter Values

 function parameters to have default values.


 Example
 If y is not passed or undefined, then y = 10.
 function myFunction(x, y = 10)
{
return x + y;
}
myFunction(5);
Function Rest Parameter

 The rest parameter (...) allows a function to treat an


indefinite number of arguments as an array:
 Example
function sum(...args)
{
let sum = 0;
for (let arg of args)
sum += arg;
return sum;
}

let x = sum(4, 9, 16, 25, 29, 100, 66, 77);


The Arguments Object
 JavaScript functions have a built-in object called the
arguments object.
 The argument object contains an array of the arguments
used when the function was called (invoked).
 This way you can simply use a function to find (for
instance) the highest value in a list of numbers:
 Example
 x = findMax(1, 123, 500, 115, 44, 88);

function findMax()
{
let max = -Infinity;
for (let i = 0; i < [Link]; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Arguments are Passed by Value
 The parameters, in a function call, are the function's
arguments.
 JavaScript arguments are passed by value: The function
only gets to know the values, not the argument's
locations.
 If a function changes an argument's value, it does not
change the parameter's original value.
 Changes to arguments are not visible (reflected)
outside the function.
Objects are Passed by Reference

 In JavaScript, object references are values.


 Because of this, objects will behave like they are passed
by reference:
 If a function changes an object property, it changes the
original value.
 Changes to object properties are visible (reflected)
outside the function.
What is a Function Expression?
 A function expression is a function assigned to a variable.
 A function expression is a way of defining a function
within an expression, rather than as a standalone
declaration.
 A function expression can be assigned to a variable,
passed as an argument to another function, or returned
from a function.
 After a function expression has been stored in a variable,
the variable can be used as a function:
 Example
 const x = function (a, b)
{
return a * b
};

let z = x(4, 3)
 The function above is actually an anonymous
function (a function without a name).
 Functions stored in variables do not need function
names. They are always invoked (called) using the
variable name.
Note
The functions above end with a semicolon because they
are a part of an executable statement.
JavaScript Arrow Functions

 Arrow Functions allow a shorter syntax for function


expressions.
 You ca skip the function keyword, the return keyword,
and the curly brackets:
 let myFunction = (a, b) => a * b;
 Arrow Functions Return Value by Default:
let hello = () => "Hello World!";
JAVASCRIPT DOM MODEL
 With the HTML DOM, JavaScript can access and change all the
elements of an HTML document.
 When a web page is loaded, the browser creates
a Document Object Model of the page.
 The HTML DOM model is constructed as a tree of Objects:
Why is DOM Required?

 The DOM is essential because:


 Dynamic Content Updates: Without reloading the page, the DOM
allows content updates (e.g., form validation, AJAX responses).
 User Interaction: It makes your webpage interactive (e.g.,
responding to button clicks, form submissions).
 Flexibility: Developers can add, modify, or remove elements and
styles in real-time.
 Cross-Platform Compatibility: It provides a standard way for
scripts to interact with web documents, ensuring browser
compatibility.
.
How the DOM Works?
 The DOM connects your webpage to JavaScript, allowing you
to:
 Access elements (like finding an <h1> tag).
 Modify content (like changing the text of a <p> tag).
 React to events (like a button click).
 Create or remove elements dynamically.
 With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
 JavaScript can change all the HTML elements in the
page
 JavaScript can change all the HTML attributes in the
page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and
attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the
page
 JavaScript can create new HTML events in the page
What is the HTML DOM?

 The HTML DOM is a standard object model


and programming interface for HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
 In other words: The HTML DOM is a standard for how
to get, change, add, or delete HTML elements.
JavaScript - HTML DOM Methods

 HTML DOM methods are actions you can perform (on HTML
Elements).
 HTML DOM properties are values (of HTML Elements) that you can
set or change.
 The HTML DOM can be accessed with JavaScript (and with other
programming languages).
 In the DOM, all HTML elements are defined as objects.
 The programming interface is the properties and methods of each
object.
 A property is a value that you can get or set (like changing the
content of an HTML element).
 A method is an action you can do (like add or deleting an HTML
element).

 Example
 The following example changes the content (the innerHTML) of
the <p> element with id="demo":
 Example
<html>
<body>

<p id="demo"></p>

<script>
[Link]("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
 In the example above, getElementById is a method, while innerHTML is
a property.
The getElementById Method

 The most common way to access an HTML element is to


use the id of the element.
 In the example above the getElementById method
used id="demo" to find the element.
The innerHTML Property

 The easiest way to get the content of an element is by


using the innerHTML property.
 The innerHTML property is useful for getting or
replacing the content of HTML elements.
 The innerHTML property can be used to get or change
any HTML element, including <html> and <body>.
JavaScript HTML DOM Elements
 Finding HTML Elements
 Often, with JavaScript, you want to manipulate HTML
elements.
 To do so, you have to find the elements first. There are
several ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections
JavaScript HTML DOM Elements

 Finding HTML Element by Id


 The easiest way to find an HTML element in the DOM, is
by using the element id.
 This example finds the element with id="intro":
 Example
 const element = [Link]("intro");
 If the element is found, the method will return the
element as an object (in element).
 If the element is not found, element will contain null.
JavaScript HTML DOM Elements
 Finding HTML Elements by Tag Name
 This example finds all <p> elements:
 Example
 const element = [Link]("p");
THANK YOU

You might also like