0% found this document useful (0 votes)
5 views

MODULE 2

This document provides an overview of JavaScript variables, operators, and data types. It explains how to declare variables using var, let, and const, and discusses various operators including arithmetic, assignment, comparison, and logical operators. Additionally, it covers JavaScript data types such as strings, numbers, booleans, arrays, and objects, along with examples and best practices for using them.

Uploaded by

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

MODULE 2

This document provides an overview of JavaScript variables, operators, and data types. It explains how to declare variables using var, let, and const, and discusses various operators including arithmetic, assignment, comparison, and logical operators. Additionally, it covers JavaScript data types such as strings, numbers, booleans, arrays, and objects, along with examples and best practices for using them.

Uploaded by

Badri Narayanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

MODULE 2

JavaScript Variables

Variables are Containers for Storing Data


JavaScript Variables can be declared in 4 ways:
 Automatically
 Using var
 Using let
 Using const
In this first example, x, y, and z are undeclared variables.
They are automatically declared when first used:
Example
x = 5;
y = 6;
z = x + y;

It is considered good programming practice to always declare variables before use.


From the examples you can guess:
 x stores the value 5
 y stores the value 6
 z stores the value 11
Example using var
var x = 5;
var y = 6;
var z = x + y;

The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
Example using let
let x = 5;
let y = 6;
let z = x + y;
Example using const
const x = 5;
const y = 6;
const z = x + y;

Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;

The two variables price1 and price2 are declared with the const keyword.
These are constant values and cannot be changed.
The variable total is declared with the let keyword.
The value total can be changed.
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.

Just Like Algebra


Just like in algebra, variables hold values:
let x = 5;
let y = 6;
Just like in algebra, variables are used in expressions:
let z = x + y;

From the example above, you can guess that the total is calculated to be 11.
JavaScript Operators
Javascript operators are used to perform different types of mathematical and logical
computations.
Examples:
The Assignment Operator = assigns values
The Addition Operator + adds values
The Multiplication Operator * multiplies values
The Comparison Operator > compares values

JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:
Assignment Examples
let x = 10;
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;

JavaScript Addition
The Addition Operator (+) adds numbers:
Adding
let x = 5;
let y = 2;
let z = x + y;

JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;
Types of JavaScript Operators
There are different types of JavaScript operators:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 String Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
 Type Operators

JavaScript Arithmetic Operators


Arithmetic Operators are used to perform arithmetic on numbers:
Arithmetic Operators Example
let a = 3;
let x = (100 + 50) * a;

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation (ES2016)

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement
Note
Arithmetic operators are fully described in the JS Arithmetic chapter.

ADVERTISEMENT

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.
The Addition Assignment Operator (+=) adds a value to a variable.
Assignment
let x = 10;
x += 5;

Operator Example Same As

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

**= x **= y x = x ** y

Note
Assignment operators are fully described in the JS Assignment chapter.
JavaScript Comparison Operators

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

Note
Comparison operators are fully described in the JS Comparisons chapter.

JavaScript String Comparison


All the comparison operators above can also be used on strings:
Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
Note that strings are compared alphabetically:
Example
let text1 = "20";
let text2 = "5";
let result = text1 < text2;

JavaScript String Addition


The + can also be used to add (concatenate) strings:
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;

The += assignment operator can also be used to add (concatenate) strings:


Example
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be:
What a very nice day

Note
When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers


Adding two numbers, will return the sum as a number like 5 + 5 = 10.
Adding a number and a string, will return the sum as a concatenated string like 5 +
"5" = "55".
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5

Note
If you add a number and a string, the result will be a string!

JavaScript Logical Operators


Operator Description

&& logical and

|| logical or

! logical not

Note
Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

Operator Description

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of an object type

Note
Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators


Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.

Operator Description Example Same as

& AND 5&1 0101 & 0001


| OR 5|1 0101 | 0001

~ NOT ~5 ~0101

^ XOR 5^1 0101 ^ 0001

<< left shift 5 << 1 0101 << 1

>> right shift 5 >> 1 0101 >> 1

>>> unsigned right shift 5 >>> 1 0101 >>> 1

JAVASCRIPT DATATYPES

JavaScript has 8 Datatypes


String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object
The Object Datatype
The object data type can contain both built-in objects, and user
defined objects:
Built-in object types can be:
objects, arrays, dates, maps, sets, intarrays, floatarrays, promises, and
more.
Examples
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
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");
Note
A JavaScript variable can hold any type of data.
The Concept of Data Types
In programming, data types is an important concept.
To be able to operate on variables, it is important to know something
about the type.
Without data types, a computer cannot safely solve this:
let x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an
error or will it produce a result?
JavaScript will treat the example above as:
let x = "16" + "Volvo";
Note
When adding a number and a string, JavaScript will treat the number as
a string.
Example
let x = 16 + "Volvo";

Example
let x = "Volvo" + 16;

JavaScript evaluates expressions from left to right. Different sequences


can produce different results:
JavaScript:
let x = 16 + 4 + "Volvo";
Result:
20Volvo

JavaScript:
let x = "Volvo" + 16 + 4;
Result:
Volvo164

In the first example, JavaScript treats 16 and 4 as numbers, until it


reaches "Volvo".
In the second example, since the first operand is a string, all operands
are treated as strings.

ADVERTISEMENT

JavaScript Types are Dynamic


JavaScript has dynamic types. This means that the same variable can
be used to hold different data types:
Example
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
// Using double quotes:
let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = 'Volvo XC60';

You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
// Single quote inside double quotes:
let answer1 = "It's alright";

// Single quotes inside double quotes:


let answer2 = "He is called 'Johnny'";

// Double quotes inside single quotes:


let answer3 = 'He is called "Johnny"';

You will learn more about strings later in this tutorial.

JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating point).
Numbers can be written with, or without decimals:
Example
// With decimals:
let x1 = 34.00;

// Without decimals:
let x2 = 34;

Exponential Notation
Extra large or extra small numbers can be written with scientific
(exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123

Note
Most programming languages have many number types:
Whole numbers (integers):
byte (8-bit), short (16-bit), int (32-bit), long (64-bit)
Real numbers (floating-point):
float (32-bit), double (64-bit).
Javascript numbers are always one type:
double (64-bit floating point).
You will learn more about numbers later in this tutorial.

JavaScript BigInt
All JavaScript numbers are stored in a 64-bit floating-point format.
JavaScript BigInt is a new datatype (ES2020) that can be used to store
integer values that are too big to be represented by a normal JavaScript
Number.
Example
let x = BigInt("123456789012345678901234567890");

JavaScript Booleans
Booleans can only have two values: true or false.
Example
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Booleans are often used in conditional testing.

JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing
three items (car names):
Example
const cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second
is [1], and so on.

JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by
commas.
Example
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};

The object (person) in the example above has 4 properties: firstName,


lastName, age, and eyeColor.

The typeof Operator


You can use the JavaScript typeof operator to find the type of a
JavaScript variable.
The typeof operator returns the type of a variable or an expression:
Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
Example
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"

Undefined
In JavaScript, a variable without a value, has the value undefined. The
type is also undefined.
Example
let car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type
will also be undefined.
Example
car = undefined; // Value is undefined, type is undefined
Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
Example
let car = ""; // The value is "", the typeof is "string"

JavaScript Objects
❮ PreviousNext ❯

Real Life Objects


In real life, objects are things like: houses, cars, people, animals, or any
other subjects.
Here is a car object example:

Car Object Properties

car.name = Fiat

car.model = 500

car.weight = 850kg

car.color = white

Object Properties
A real life car has properties like weight and color:
car.name = Fiat, car.model = 500, car.weight = 850kg, car.color = white.
Car objects have the same properties, but the values differ from car to
car.
Object Methods
A real life car has methods like start and stop:
car.start(), car.drive(), car.brake(), car.stop().
Car objects have the same methods, but the methods are performed at
different times.

JavaScript Variables
JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
Example
let car = "Fiat";

JavaScript Objects
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to an object named
car:
Example
const car = {type:"Fiat", model:"500", color:"white"};

Note:
It is a common practice to declare objects with the const keyword.
Learn more about using const with objects in the chapter: JS Const.

JavaScript Object Definition


How to Define a JavaScript Object
 Using an Object Literal
 Using the new Keyword
 Using an Object Constructor

JavaScript Object Literal


An object literal is a list of name:value pairs inside curly braces {}.
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

Note:
name:value pairs are also called key:value pairs.
object literals are also called object initializers.

Creating a JavaScript Object


These examples create a JavaScript object with 4 properties:
Examples
// Create an Object
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};

Spaces and line breaks are not important. An object initializer can span
multiple lines:
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

This example creates an empty JavaScript object, and then adds 4


properties:
// Create an Object
const person = {};

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

Using the new Keyword


This example create a new JavaScript object using new Object(), and
then adds 4 properties:
Example
// Create an Object
const person = new Object();

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

Note:
The examples above do exactly the same.
But, there is no need to use new Object().
For readability, simplicity and execution speed, use the object
literal method.

Object Properties
The named values, in JavaScript objects, are called properties.
Property Value

firstName John

lastName Doe

Age 50

eyeColor blue

Objects written as name value pairs are similar to:


 Associative arrays in PHP
 Dictionaries in Python
 Hash tables in C
 Hash maps in Java
 Hashes in Ruby and Perl

Accessing Object Properties


You can access object properties in two ways:
objectName.propertyName
objectName["propertyName"]
Examples
person.lastName;

person["lastName"];

JavaScript Object Methods


Methods are actions that can be performed on objects.
Methods are function definitions stored as property values.
Property Property Value

firstName John

lastName Doe

Age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}

Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

In the example above, this refers to the person object:


this.firstName means the firstName property of person.
this.lastName means the lastName property of person.

In JavaScript, Objects are King.


If you Understand Objects, you Understand JavaScript.
Objects are containers for Properties and Methods.
Properties are named Values.
Methods are Functions stored as Properties.
Properties can be primitive values, functions, or even other objects.
In JavaScript, almost "everything" is an object.
 Objects are objects
 Maths are objects
 Functions are objects
 Dates are objects
 Arrays are objects
 Maps are objects
 Sets are objects
All JavaScript values, except primitives, are objects.

JavaScript Primitives
A primitive value is a value that has no properties or methods.
3.14 is a primitive value
A primitive data type is data that has a primitive value.
JavaScript defines 7 types of primitive data types:
 string
 number
 boolean
 null
 undefined
 symbol
 bigint
Immutable
Primitive values are immutable (they are hardcoded and cannot be
changed).
if x = 3.14, you can change the value of x, but you cannot change the
value of 3.14.

Value Type Comment


"Hello" string "Hello" is always "Hello"

3.14 number 3.14 is always 3.14

True boolean true is always true

False boolean false is always false

Null null (object) null is always null

undefined undefined undefined is always undefined

JavaScript Objects are Mutable


Objects are mutable: They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of
person:
const x = person;
The object x is not a copy of person. The object x is person.
The object x and the object person share the same memory address.
Any changes to x will also change person:
Example
//Create an Object
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}

// Create a copy
const x = person;
// Change Age in both
x.age = 10;

Block Scope
Before ES6 (2015), JavaScript variables had only Global
Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside
the block:
Example
{
let x = 2;
}
// x can NOT be used here
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the
block.
Example
{
var x = 2;
}
// x CAN be used here

Local Scope
Variables declared within a JavaScript function, are LOCAL to the
function:
Example
// code here can NOT use carName

function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}

// code here can NOT use carName

Local variables have Function Scope:


They can only be accessed from within the function.
Since local variables are only recognized inside their functions, variables
with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the
function is completed.

Function Scope
JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from
outside the function.
Variables declared with var, let and const are quite similar when declared
inside a function.
They all have Function Scope:
function myFunction() {
var carName = "Volvo"; // Function Scope
}
function myFunction() {
let carName = "Volvo"; // Function Scope
}
function myFunction() {
const carName = "Volvo"; // Function Scope
}

Global JavaScript Variables


A variable declared outside a function, becomes GLOBAL.
Example
let carName = "Volvo";
// code here can use carName

function myFunction() {
// code here can also use carName
}
A global variable has Global Scope:
All scripts and functions on a web page can access it.

Global Scope
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript
program.
Variables declared with var, let and const are quite similar when declared
outside a block.
They all have Global Scope:
var x = 2; // Global scope
let x = 2; // Global scope
const x = 2; // Global scope

JavaScript Variables
In JavaScript, objects and functions are also variables.
Scope determines the accessibility of variables, objects, and functions
from different parts of the code.

Automatically Global
If you assign a value to a variable that has not been declared, it will
automatically become a GLOBAL variable.
This code example will declare a global variable carName, even if the
value is assigned inside a function.
Example
myFunction();

// code here can use carName

function myFunction() {
carName = "Volvo";
}

Strict Mode
All modern browsers support running JavaScript in "Strict Mode".
You will learn more about how to use strict mode in a later chapter of this
tutorial.
In "Strict Mode", undeclared variables are not automatically global.

Global Variables in HTML


With JavaScript, the global scope is the JavaScript environment.
In HTML, the global scope is the window object.
Global variables defined with the var keyword belong to the window
object:
Example
var carName = "Volvo";
// code here can use window.carName

Global variables defined with the let keyword do not belong to the
window object:
Example
let carName = "Volvo";
// code here can not use window.carName

Do NOT create global variables unless you intend to.


Your global variables (or functions) can overwrite window variables (or
functions).
Any function, including the window object, can overwrite your global
variables and functions.

The Lifetime of JavaScript Variables


The lifetime of a JavaScript variable starts when it is declared.
Function (local) variables are deleted when the function is completed.
In a web browser, global variables are deleted when you close the
browser window (or tab).

Function Arguments
Function arguments (parameters) work as local variables inside
functions.

JAVA SCRIPT EVENTS

HTML Events
An HTML event can be something the browser does, or something a
user does.
Here are some examples of HTML events:
 An HTML web page has finished loading
 An HTML input field was changed
 An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
In the following example, an onclick attribute (with code), is added to
a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>

In the example above, the JavaScript code changes the content of the
element with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>

JavaScript code is often several lines long. It is more common to see


event attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>

Common HTML Events


Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element


onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

JavaScript Event Handlers


Event handlers can be used to handle and verify user input, user
actions, and browser actions:
 Things that should be done every time a page loads
 Things that should be done when the page is closed
 Action that should be performed when a user clicks a button
 Content that should be verified when a user inputs data
 And more ...
Many different methods can be used to let JavaScript work with events:
 HTML event attributes can execute JavaScript code directly
 HTML event attributes can call JavaScript functions
 You can assign your own event handler functions to HTML
elements
 You can prevent events from being sent or being handled

JAVA SCRIPT FUNCTIONS


A JavaScript function is a block of code designed to perform a particular
task.
A JavaScript function is executed when "something" invokes it (calls it).
Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}

JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly
brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function
definition.
Function arguments are the values received by the function when it is
invoked.
Inside the function, the arguments (the parameters) behave as local
variables.

Function Invocation
The code inside the function will execute when
"something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.

ADVERTISEMENT

Function Return
When JavaScript reaches a return statement, the function will stop
executing.
If the function was invoked from a statement, JavaScript will "return" to
execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned"
back to the "caller":
Example
Calculate the product of two numbers, and return the result:
// Function is called, the return value will end up in x
let x = myFunction(4, 3);

function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

Why Functions?
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.

The () Operator
The () operator invokes (calls) the function:
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}

let value = toCelsius(77);

Accessing a function with incorrect parameters can return an incorrect


answer:
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}

let value = toCelsius();

Accessing a function without () returns the function and not the function
result:
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}

let value = toCelsius;

Note
As you see from the examples above, toCelsius refers to the function
object, and toCelsius() refers to the function result.

Functions Used as Variable Values


Functions can be used the same way as you use variables, in all types
of formulas, assignments, and calculations.
Example
Instead of using a variable to store the return value of a function:
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
You can use the function directly, as a variable value:
let text = "The temperature is " + toCelsius(77) + " Celsius";

Local Variables
Variables declared within a JavaScript function, become LOCAL to the
function.
Local variables can only be accessed from within the function.
Example
// code here can NOT use carName

function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}

// code here can NOT use carName

Since local variables are only recognized inside their functions, variables
with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the
function is completed.

JavaScript Loops
Loops are handy, if you want to run the same code over and over again,
each time with a different value.
Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}

Different Kinds of Loops


JavaScript supports different kinds of loops:
 for - loops through a block of code a number of times
 for/in - loops through the properties of an object
 for/of - loops through the values of an iterable object
 while - loops through a block of code while a specified condition is
true
 do/while - also loops through a block of code while a specified
condition is true

The For Loop


The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Expression 1 is executed (one time) before the execution of the code
block.
Expression 2 defines the condition for executing the code block.
Expression 3 is executed (every time) after the code block has been
executed.
Example
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}

T
From the example above, you can read:
Expression 1 sets a variable before the loop starts (let i = 0).
Expression 2 defines the condition for the loop to run (i must be less
than 5).
Expression 3 increases a value (i++) each time the code block in the
loop has been executed.

ADVERTISEMENT

How to use Expression 1


Expression 1 is used to initialize the variable(s) used in the loop (let i =
0).
But, expression 1 is optional.
You can omit expression 1 when your values are set before the loop
starts:
Example
let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}

You can intiate many values in expression 1 (separated by comma):


Example
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}

How to use Expression 2


Expression 2 is used to evaluate the condition of the initial variable (i <
len).
But, expression 2 is also optional.
If expression 2 returns true, the loop will start over again. If it returns
false, the loop will end.
Note
If you omit expression 2, you must provide a break inside the loop.
Otherwise the loop will never end. This will crash your browser. Read
about breaks in a later chapter of this tutorial.

How to use Expression 3


Expression 3 increments the value of the initial variable (i++).
But, expression 3 is also optional.
Expression 3 can do anything like negative increment (i--), positive
increment (i = i + 15), or anything else.
Expression 3 can also be omitted (like when you increment your values
inside the loop):
Example
let i = 0;
let len = cars.length;
let text = "";
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}

Loop Scope
Using var in a loop:
Example
var i = 5;

for (var i = 0; i < 10; i++) {


// some code
}

// Here i is 10

Using let in a loop:


Example
let i = 5;

for (let i = 0; i < 10; i++) {


// some code
}

// Here i is 5
In the first example, using var, the variable declared in the loop
redeclares the variable outside the loop.
In the second example, using let, the variable declared in the loop does
not redeclare the variable outside the loop.
When let is used to declare the i variable in a loop, the i variable will only
be visible within the loop.
JAVASCRIPT ARRAYS

JavaScript Arrays

An array is a special variable, which can hold more than one value:
const cars = ["Saab", "Volvo", "BMW"];

Why Use Arrays?


If you have a list of items (a list of car names, for example), storing the
cars in single variables could look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
However, what if you want to loop through the cars and find a specific
one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can
access the values by referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
const array_name = [item1, item2, ...];
It is a common practice to declare arrays with the const keyword.
Learn more about const with arrays in the chapter: JS Array Const.
Example
const cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span
multiple lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];

You can also create an array, and then provide the elements:
Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:
Example
const cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same.
There is no need to use new Array().
For simplicity, readability and execution speed, use the array literal
method.

Accessing Array Elements


You access an array element by referring to the index number:
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
Note: Array indexes start with 0.
[0] is the first element. [1] is the second element.

Changing an Array Element


This statement changes the value of the first element in cars:
cars[0] = "Opel";
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";

Converting an Array to a String


The JavaScript method toString() converts an array to a string of
(comma separated) array values.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array
name:
Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;

Arrays are Objects


Arrays are a special type of objects. The typeof operator in JavaScript
returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this
example, person[0] returns John:
Array:
const person = ["John", "Doe", 46];

Objects use names to access its "members". In this


example, person.firstName returns John:
Object:
const person = {firstName:"John", lastName:"Doe", age:46};

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same
Array.
You can have objects in an Array. You can have functions in an Array.
You can have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties
and methods:
cars.length // Returns the number of elements
cars.sort() // Sorts the array
Array methods are covered in the next chapters.

The length Property


The length property of an array returns the length of an array (the
number of array elements).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;

The length property is always one more than the highest array index.

Accessing the First Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];

Accessing the Last Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[fruits.length - 1];

Looping Array Elements


One way to loop through an array, is using a for loop:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";


for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

You can also use the Array.forEach() function:


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

let text = "<ul>";


fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}

Adding Array Elements


The easiest way to add a new element to an array is using
the push() method:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits

New element can also be added to an array using the length property:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits

WARNING !
Adding elements with high indexes can create undefined "holes" in an
array:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits

Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
Example
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"

WARNING !!
If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect
results.
Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person.length; // Will return 0
person[0]; // Will return undefined

The Difference Between Arrays and Objects


In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


 JavaScript does not support associative arrays.
 You should use objects when you want the element names to
be strings (text).
 You should use arrays when you want the element names to
be numbers.

JavaScript new Array()


JavaScript has a built-in array constructor new Array().
But you can safely use [] instead.
These two different statements both create a new empty array named
points:
const points = new Array();
const points = [];
These two different statements both create a new array containing 6
numbers:
const points = new Array(40, 100, 1, 5, 25, 10);
const points = [40, 100, 1, 5, 25, 10];

The new keyword can produce some unexpected results:


// Create an array with three elements:
const points = new Array(40, 100, 1);

// Create an array with two elements:


const points = new Array(40, 100);

// Create an array with one element ???


const points = new Array(40);

A Common Error
const points = [40];
is not the same as:
const points = new Array(40);
// Create an array with one element:
const points = [40];

// Create an array with 40 undefined elements:


const points = new Array(40);

How to Recognize an Array


A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns "object":
const fruits = ["Banana", "Orange", "Apple"];
let type = typeof fruits;
The typeof operator returns object because a JavaScript array is an
object.
Solution 1:
To solve this problem ECMAScript 5 (JavaScript 2009) defined a new
method Array.isArray():
Array.isArray(fruits);

Solution 2:
The instanceof operator returns true if an object is created by a given
constructor:
const fruits = ["Banana", "Orange", "Apple"];

(fruits instanceof Array);

Nested Arrays and Objects


Values in objects can be arrays, and values in arrays can be objects:
Example
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}
To access arrays inside arrays, use a for-in loop for each array:
Example
for (let i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}

JavaScript Forms

JavaScript Form Validation


HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and
returns false, to prevent the form from being submitted:
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
The function can be called when the form is submitted:
HTML Form Example
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

JavaScript Can Validate Numeric Input


JavaScript is often used to validate numeric input:
Please input a number between 1 and 10
Submit

Automatic HTML Form Validation


HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form
from being submitted:
HTML Form Example
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
Automatic HTML form validation does not work in Internet Explorer 9 or
earlier.

Data Validation
Data validation is the process of ensuring that user input is clean,
correct, and useful.
Typical validation tasks are:
 has the user filled in all required fields?
 has the user entered a valid date?
 has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in
many different ways.
Server side validation is performed by a web server, after input has
been sent to the server.
Client side validation is performed by a web browser, before input is
sent to a web server.

HTML Constraint Validation


HTML5 introduced a new HTML validation concept called constraint
validation.
HTML constraint validation is based on:
 Constraint validation HTML Input Attributes
 Constraint validation CSS Pseudo Selectors
 Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

Attribute Description

disabled Specifies that the input element should be disabled


max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

Constraint Validation CSS Pseudo Selectors

Selector Description

:disabled Selects input elements with the "disabled" attribute sp

:invalid Selects input elements with invalid values

:optional Selects input elements with no "required" attribute spe

:required Selects input elements with the "required" attribute sp

:valid Selects input elements with valid values

DOM
JavaScript HTML DOM Document
The HTML DOM document object is the owner of all other objects in
your web page.

The HTML DOM Document Object


The document object represents your web page.
If you want to access any element in an HTML page, you always start
with accessing the document object.
Below are some examples of how you can use the document object to
access and manipulate HTML.

Finding HTML Elements

Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements

Property Description

element.innerHTML = new html content Change the inner HTML of an ele

element.attribute = new value Change the attribute value of an

element.style.property = new style Change the style of an HTML ele

Method Description

element.setAttribute(attribute, value) Change the attribute value of an

Adding and Deleting Elements

Method Description
document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

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

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 = document.getElementById("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.

Finding HTML Elements by Tag Name


This example finds all <p> elements:
Example
const element = document.getElementsByTagName("p");
This example finds the element with id="main", and then finds all <p> elements
inside "main":
Example
const x = document.getElementById("main");
const y = x.getElementsByTagName("p");

Finding HTML Elements by Class Name


If you want to find all HTML elements with the same class name,
use getElementsByClassName().
This example returns a list of all elements with class="intro".
Example
const x = document.getElementsByClassName("intro");

Finding HTML Elements by CSS Selectors


If you want to find all HTML elements that match a specified CSS selector (id, class
names, types, attributes, values of attributes, etc), use
the querySelectorAll() method.
This example returns a list of all <p> elements with class="intro".
Example
const x = document.querySelectorAll("p.intro");

Finding HTML Elements by HTML Object Collections


This example finds the form element with id="frm1", in the forms collection, and
displays all element values:
Example
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;

A simple UI design
A simple UI design in JavaScript typically involves manipulating HTML elements
directly using JavaScript to create interactive components like buttons, text fields,
and alerts, often with basic styling using CSS, without relying on complex
frameworks like React or Angular; essentially, directly changing the content and
appearance of a webpage based on user interaction.
Key elements of a simple UI with JavaScript:
 HTML Structure:
Create the basic layout of your UI using HTML tags like <div>, <input>, <button>,
and <p> to define the elements where content will be displayed and user interaction
will occur.
 JavaScript DOM Manipulation:
 Accessing
Elements: Use document.getElementById(), document.querySelector()
to select specific HTML elements on the page to modify them with
JavaScript.
 Modifying Content: Change text content using .textContent or
innerHTML to update what is displayed within an element.
 Styling: Apply CSS styles dynamically using .style.property = 'value' to
change color, font, or positioning of elements.
 Event Listeners: Add event listeners like addEventListener('click',
function) to respond to user actions like button clicks, mouse hovers, or
form submissions.

Example: A simple button that changes text when clicked:


Code
<button id="myButton">Click Me</button>

<p id="result"></p>
Code
const button = document.getElementById('myButton');

const result = document.getElementById('result');

button.addEventListener('click', function() {

result.textContent = "Button clicked!";

});
Explanation:
 HTML:
A button with the ID "myButton" and a paragraph with the ID "result" are created.
 JavaScript:
 The getElementById function gets references to the button and
paragraph elements.
 An event listener is added to the button: when clicked, the function
inside is executed.
 Inside the click function, the text content of the paragraph is updated to
"Button clicked!".
Important considerations for simple UI design:
 Accessibility: Ensure your UI is accessible to users with disabilities by using
appropriate ARIA attributes and semantic HTML tags.
 Responsiveness: Design your UI to adapt to different screen sizes using
CSS media queries.
 Visual Hierarchy: Organize content with clear visual cues to guide the user's
attention.

What is JSON?
JSON
JSON stands for JavaScript Object Notation
JSON is a lightweight format for storing and transporting data
JSON is often used when data is sent from a server to a web page
JSON is "self-describing" and easy to understand

JSON Example
This example defines an employees object: an array of 3 employee records
(objects):
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}

JSON Syntax Rules


 Data is in name/value pairs
 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays

JavaScript Object Notation


The JSON format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, a JavaScript program can easily convert JSON data into
native JavaScript objects.
The JSON syntax is derived from JavaScript object notation syntax, but the JSON
format is text only. Code for reading and generating JSON data can be written in any
programming language.

JSON Data - A Name and a Value


JSON data is written as name/value pairs, just like JavaScript object properties.
A name/value pair consists of a field name (in double quotes), followed by a colon,
followed by a value:
"firstName":"John"
JSON names require double quotes. JavaScript names do not.

JSON Objects
JSON objects are written inside curly braces.
Just like in JavaScript, objects can contain multiple name/value pairs:
{"firstName":"John", "lastName":"Doe"}

JSON Arrays
JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).

S
Converting a JSON Text to a JavaScript Object
A common use of JSON is to read data from a web server, and display the data in a
web page.
For simplicity, this can be demonstrated using a string as input.
First, create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Then, use the JavaScript built-in function JSON.parse() to convert the string into a
JavaScript object:
var obj = JSON.parse(text);
Finally, use the new JavaScript object in your page:
Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

You might also like