[Go to site: main page, start]

0% found this document useful (0 votes)
12 views56 pages

Introduction to JavaScript Basics

JavaScript is a lightweight, dynamic programming language primarily used for creating interactive web pages and is integrated with HTML. It allows client-side scripting to enhance user experience by providing immediate feedback and reducing server interactions. The document covers JavaScript syntax, variable declaration, operators, data types, and methods for implementing JavaScript in HTML documents.

Uploaded by

dudehackster
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)
12 views56 pages

Introduction to JavaScript Basics

JavaScript is a lightweight, dynamic programming language primarily used for creating interactive web pages and is integrated with HTML. It allows client-side scripting to enhance user experience by providing immediate feedback and reducing server interactions. The document covers JavaScript syntax, variable declaration, operators, data types, and methods for implementing JavaScript in HTML documents.

Uploaded by

dudehackster
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

MODULE III
JavaScript

1
JavaScript

What is JavaScript ?
 JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages.
 It allow client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.

 JavaScript is a lightweight, interpreted programming language.

 Designed for creating dynamic web applications.

 Complementary to and integrated with HTML.

 Open and cross-platform

Syntax:

<script ...>
JavaScript code
</script>
Example:
<html>
<body>
<script language="javascript" type="text/javascript">

[Link]("Hello World!");

</script>
</body>
</html>
Client-side JavaScript
 Client-side JavaScript is the most common form of javascript language. The script
should be included in HTML document for the code to be interpreted by the browser.

 Dynamic web pages can be created by integrating javascript code to HTML content.

 The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form [Link] JavaScript code is executed when the
user submits the form, and only if all the entries are valid, they would be submitted to
the Web Server.

2
JavaScript

 JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.

Advantages of JavaScript
The merits of using JavaScript are −

 Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.

 Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.

 Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.

 Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

Implementation of Java script in HTML Page.


There is a flexibility given to include JavaScript code anywhere in an HTML document. However
the most preferred ways to include JavaScript in an HTML file are as follows −

1. Script in <head>...</head> section.

2. Script in <body>...</body> section.

3. Script in <body>...</body> and <head>...</head> sections.

4. Script in an external file and then include in <head>...</head> section.

1. JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks somewhere, then
you will place that script in the head as follows −

<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>

3
JavaScript

<body>
<input type = "button" value = "Say Hello" />
</body>
</html>

2. JavaScript in <body>...</body> section


If you need a script to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, you would not have
any function defined using JavaScript. Take a look at the following code.

<html>
<head>
</head>

<body>
<script type = "text/javascript">
[Link]("Hello World")
</script>

<p>This is web page body </p>


</body>
</html>

4
JavaScript

3. JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows −

<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>

<body>
<script type = "text/javascript">

[Link]("Hello World")
</script>

<input type = "button" value = "Say Hello" />


</body>
</html>

5
JavaScript

4. JavaScript in External File


As you begin to work more extensively with JavaScript, you will be likely to find that there are
cases where you are reusing identical JavaScript code on multiple pages of a site.

You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it
into your HTML files.

Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute.

<html>
<head>
<script type = "text/javascript" src = "[Link]" ></script>
</head>

<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source
code in a simple text file with the extension ".js" and then include that file as shown above.

6
JavaScript

For example, you can keep the following content in [Link] file and then you can
use sayHello function in your HTML file after including the [Link] file.

function sayHello()
{
alert("Hello World")
}

JavaScript Variables
 Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.
 Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.

<script type = "text/javascript">


var money;
var name;
</script>
You can also declare multiple variables with the same var keyword as follows −

<script type = "text/javascript">


var money,
name;
</script>

You can assign a value at the time of initialization as follows.

<script type = "text/javascript">


var name = "Ali";
var money;
money = 2000.50;
</script>

7
JavaScript

JavaScript Variable Scope


The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.

 Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.

 Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.

Operators in Java Script


Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is
called the operator. JavaScript supports the following types of operators.

1. Arithmetic Operators

2. Comparison Operators

3. Logical (or Relational) Operators

4. Assignment Operators

5. Conditional (or ternary) Operators

1. Arithmetic Operators
JavaScript supports the following arithmetic operators − Assume variable A holds 10 and
variable B holds 20, then −

[Link] Operator and Description

1 + (Addition)
Adds two operands
Ex: A + B will give 30

8
JavaScript

2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10

3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200

4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2

5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11

7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

2. Comparison Operators
JavaScript supports the following comparison operators − Assume variable A holds 10 and
variable B holds 20, then −

[Link] Operator and Description

1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.

2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal,

9
JavaScript

then the condition becomes true.


Ex: (A != B) is true.

3 > (Greater than)


Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.

4 < (Less than)


Checks if the value of the left operand is less than the value of the right operand,
if yes, then the condition becomes true.
Ex: (A < B) is true.

5 >= (Greater than or Equal to)


Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

6 <= (Less than or Equal to)


Checks if the value of the left operand is less than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

3. Logical Operators
JavaScript supports the following logical operators −Assume variable A holds 10 and variable B
holds 20, then −

[Link] Operator and Description

1 && (Logical AND)


If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.

10
JavaScript

3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Ex: ! (A && B) is false.

4. Bitwise Operators
JavaScript supports the following bitwise operators −Assume variable A holds 2 and variable B
holds 3, then −

[Link] Operator and Description

1 & (Bitwise AND)


It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.

2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.

5 << (Left Shift)


It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a value
left by one position is equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.

6 >> (Right Shift)


Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand.
Ex: (A >> 1) is 1.

7 >>> (Right shift with Zero)


This operator is just like the >> operator, except that the bits shifted in on the
left are always zero.
Ex: (A >>> 1) is 1.

11
JavaScript

5. Assignment Operators
JavaScript supports the following assignment operators −

[Link] Operator and Description

1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

2 += (Add and Assignment)


It adds the right operand to the left operand and assigns the result to the left
operand.
Ex: C += A is equivalent to C = C + A

3 −= (Subtract and Assignment)


It subtracts the right operand from the left operand and assigns the result to the
left operand.
Ex: C -= A is equivalent to C = C - A

4 *= (Multiply and Assignment)


It multiplies the right operand with the left operand and assigns the result to the
left operand.
Ex: C *= A is equivalent to C = C * A

5 /= (Divide and Assignment)


It divides the left operand with the right operand and assigns the result to the
left operand.
Ex: C /= A is equivalent to C = C / A

6 %= (Modules and Assignment)


It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.

12
JavaScript

7. Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.

[Link] Operator and Description

1 ? : (Conditional )

If Condition is true? Then value X : Otherwise value Y

8. typeof Operator
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.

Here is a list of the return values for the typeof Operator.

JavaScript Data types

One of the most fundamental characteristics of a programming language is the set of data
types it supports. These are the type of values that can be represented and manipulated in a
programming language.

JavaScript allows you to work with three primitive data types −

 Numbers e.g. 123, 120.50 etc.

 Strings of text e.g. "This text string" etc.

 Boolean e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data
type known as object.

13
JavaScript

String Methods and Properties in JavaScript


In JavaScript, methods and properties are also available to primitive values, because JavaScript
treats primitive values as objects when executing methods and properties.

1. String Length :-The length property returns the length of a string:

Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = [Link];
Output : sln=26

2. indexOf() method returns the index of (the position of) the first occurrence of a specified
text in a string:
Example
var str = "Please locate where 'locate' occurs!";
var pos = [Link]("locate");
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...
Pos returnd the value 8

3. Searching for a String in a String :The search() method searches a string for a specified
value and returns the position of the match:

Example
var str = "Please locate where 'locate' occurs!";
var pos = [Link]("locate");

4. Extracting String Parts :There are 3 methods for extracting a part of a string:

1. slice(start, end)
2. substring(start, end)
3. substr(start, length)

14
JavaScript

The slice() Method

slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Example
var str = "Apple, Banana, Kiwi";
var res = [Link](7, 13);
The result of res will be:
Banana

The substring() Method

substring() is similar to slice().


The difference is that substring() cannot accept negative indexes.
Example
var str = "Apple, Banana, Kiwi";
var res = [Link](7, 13);
The result of res will be:Banana

The substr() Method

substr() is similar to slice().


The difference is that the second parameter specifies the length of the extracted part.
Example
var str = "Apple, Banana, Kiwi";
var res = [Link](7, 6);
The result of res will be:Banana

5. Replacing String Content

The replace() method replaces a specified value with another value in a string:

Example
str = "Please visit Microsoft!";
var n = [Link]("Microsoft", "MACAS");
Output : Please visit MACAS

15
JavaScript

6. Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

Example
var text1 = "Hello World!"; // String
var text2 = [Link](); // text2 is text1 converted to upper
A string is converted to lower case with toLowerCase():

Example
var text1 = "Hello World!"; // String
var text2 = [Link](); // text2 is text1 converted to lower

7. The concat() Method


concat() joins two or more strings:

Example
var text1 = "Hello";
var text2 = "World";
var text3 = [Link](" ", text2);
The concat() method can be used instead of the plus operator. These two lines do the same:

8. [Link]()
[Link]() removes whitespace from both sides of a string.
Example
var str = " Hello World! ";
alert([Link]());

9. Extracting String Characters


There are 3 methods for extracting string characters:
charAt(position)
charCodeAt(position)
The charAt() Method
The charAt() method returns the character at a specified index (position) in a string:
Example
var str = "HELLO WORLD";

16
JavaScript

[Link](0); // returns H
The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:

Example
var str = "HELLO WORLD";

[Link](0); // returns 72

Array in Java Script


The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of the same
type.

Syntax
Use the following syntax to create an Array object –

var a = new Array( "apple", "orange", "mango" );

The Array parameter is a list of strings or integers. When you specify a single numeric
parameter with the Array constructor, you specify the initial length of the array. The maximum
length allowed for an array is 4,294,967,295.

You can create array by simply assigning values as follows −

var a = [ "apple", "orange", "mango" ];

You will use ordinal numbers to access and to set values inside an array as follows.

a[0] is the first element


a[1] is the second element
a[2] is the third element

17
JavaScript

Array Properties
Here is a list of the properties of the Array object along with their description.

[Link]. Property & Description

1 constructor

Returns a reference to the array function that created the object.

2 index

The property represents the zero-based index of the match in the string

3 input

This property is only present in arrays created by regular expression matches.

4 length

Reflects the number of elements in an array.

In the following sections, we will have a few examples to illustrate the usage of Array
properties.

FUNTIONS IN JAVASCRIPT
 A function is a group of programming code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again. It helps
programmers in writing modular codes. Functions allow a programmer to divide a big
program into a number of small and manageable functions.

 Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions.

 JavaScript allows us to write our own functions as well. This section explains how to
write your own functions in JavaScript.

18
JavaScript

Function Definition

Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax
The basic syntax is shown here.

<script type="text/javascript">
function functionname(parameter-list)
{
statements
}
</script>

Example
Try the following example. It defines a function called sayHello that takes no parameters –

<script type="text/javascript">
function sayHello()
{
alert("Hello there");
}
</script>

Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name
of that function as shown in the following code.

19
JavaScript

<html>
<head>

<script type="text/javascript">
function sayHello()
{
[Link] ("Hello there!");
}
</script>

</head>
<body>
<p>Click the following button to call the function</p>

<form>
<input type="button" value="Say Hello">
</form>

<p>Use different text in write method and then try...</p>


</body>
</html>

Objects in JavaScript
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.

Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data
types, such as another object. Object properties are usually variables that are used internally
in the object's methods, but can also be globally visible variables that are used throughout the
page.

The syntax for adding a property to an object is −

[Link] = propertyValue;

20
JavaScript

For example − The following code gets the document title using the "title"property of
the document object.

var str = [Link];

Object Methods
Methods are the functions that let the object do something or let something be done to it.
There is a small difference between a function and a method – at a function is a standalone
unit of statements and a method is attached to an object and can be referenced by
the this keyword.

For example − Following is a simple example to show how to use the write() method of
document object to write any content on the document.

[Link]("This is test");

The Date Object

The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.

You can use any of the following syntaxes to create a Date object using Date() constructor.

 new Date( )
 new Date(milliseconds)
 new Date(datestring)

21
JavaScript

Conditional Statements in JAVASCRIPT


JavaScript supports the following forms of if..else statement −

1. if statement

2. if...else statement

3. if...else if... statement.

1. if statement
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.

Syntax
The syntax for a basic if statement is as follows −

if (expression)
{
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the
times, you will use comparison operators while making decisions.

22
JavaScript

Example
Try the following example to understand how the if statement works.

<script type = "text/javascript">

var age = 20;

if( age > 18 )


{
[Link]("<b>Qualifies for driving</b>");
}
</script>
Output
Qualifies for driving
Set the variable to different value and then try...

2. if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.

Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.

Example
Try the following code to learn how to implement an if-else statement in JavaScript.

<script type = "text/javascript">

var age = 15;

23
JavaScript

if( age > 18 )


{
[Link]("<b>Qualifies for driving</b>");
}
else
{
[Link]("<b>Does not qualify for driving</b>");
}
</script>
Output
Does not qualify for driving
Set the variable to different value and then try...

3. if...else if... statement


The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.

Syntax
The syntax of an if-else-if statement is as follows −

if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a
part of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.

24
JavaScript

Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.

<script type = "text/javascript">


var book = "maths";
if( book == "history" )
{
[Link]("<b>History Book</b>");
}
else if( book == "maths" )
{
[Link]("<b>Maths Book</b>");
}
else if( book == "economics" )
{
[Link]("<b>Economics Book</b>");
}
Else
{
[Link]("<b>Unknown Book</b>");
}
</script>

Output
Maths Book
Set the variable to different value and then try...
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway
branch. However, this is not always the best solution, especially when all of the branches
depend on the value of a single variable.

Starting with JavaScript 1.2, you can use a switch statement which handles exactly this
situation, and it does so more efficiently than repeated if...else ifstatements.

4. switch Statement
The following flow chart explains a switch-case statement works.

The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches,
a default condition will be used.

25
JavaScript

switch (expression)
{
case condition 1:
statement(s)
break;

case condition 2:
statement(s)
break;
...

case condition n:
statement(s)
break;

default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.

We will explain break statement in Loop Control chapter.

Example
Try the following example to implement switch-case statement.

<script type = "text/javascript">


var grade = 'A';
[Link]("Entering switch block<br />");
switch (grade)
{
case 'A':
[Link]("Good job<br />");
break;

case 'B':
[Link]("Pretty good<br />");
break;

case 'C':
[Link]("Passed<br />");
break;

case 'D':

26
JavaScript

[Link]("Not so good<br />");


break;

case 'F':
[Link]("Failed<br />");
break;

default:
[Link]("Unknown grade<br />")
}
[Link]("Exiting switch block");
</script>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...

Looping in JavaScript
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines.

JavaScript supports all the necessary loops to ease down the pressure of programming.

2. The while Loop


The most basic loop in JavaScript is the while loop which would be discussed in this chapter.
The purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.

Syntax
The syntax of while loop in JavaScript is as follows −

while (expression)
{
Statement(s) to be executed if expression is true
}

27
JavaScript

Example
Try the following example to implement while loop.

<script type="text/javascript">
var i = 0;
while (i < 10)
{
[Link]( i + "<br />");
count++;
}

</script>

Output
1
2
3
4
5
6
7
8
9
10
3. The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Syntax
The syntax for do-while loop in JavaScript is as follows −

Do
{
Statement(s) to be executed;
}
while (expression);

28
JavaScript

Example
<script type="text/javascript">
var i= 0;
do
{
[Link]( i + "<br />");
i++;
}
while (i < 5);
</script>

Output
1
2
3
4
5
4. The 'for' loop
It is the most compact form of looping. It includes the following three important parts −
 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.

 The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.

 The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by semicolons.

Syntax
The syntax of for loop is JavaScript is as follows −

for (initialization; test condition; iteration statement)


{
Statement(s) to be executed if test condition is true
}

29
JavaScript

Example
Try the following example to learn how a for loop works in JavaScript.

<script type = "text/javascript">


var i;

for(i = 0; i < 5; i++)


{
[Link]( i );
[Link]("<br />");
}
</script>

Output
1
2
3
4
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a
loop early, breaking out of the enclosing curly braces.

Example
The following example illustrates the use of a break statement with a while loop. Notice how
the loop breaks out early once x reaches 5 and reaches to [Link] (..) statement just
below to the closing curly brace −

<script type="text/javascript">
var x = 1;
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
[Link]( x + "<br />");
}
</script>

30
JavaScript

Output
1
2
3
4
5
The continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the loop
and skip the remaining code block. When a continuestatement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise the control comes out of the loop.

Example
This example illustrates the use of a continue statement with a while loop. Notice how
the continue statement is used to skip printing when the index held in variable x reaches 5 −

<script type="text/javascript">
var x = 1;
while (x < 10)
{
x = x + 1;

if (x == 5){
continue; // skip rest of the loop body
}
[Link]( x + "<br />");
}
</script>

Output
Entering the loop
2
3
4
6
7
8
9
10

31
JavaScript

Event Driven Programming In JAVASCRIPT

What is an Event ?
 JavaScript's interaction with HTML is handled through events that occur when the user
or the browser manipulates a page.

 When the page loads, it is called an event. When the user clicks a button, that click too
is an event. Other examples include events like pressing any key, closing a window,
resizing a window, etc.

 Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.

 Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.

Here we will see a few examples to understand a relation between Event and JavaScript –

1. onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.

Example
Try the following example.

32
JavaScript

<html>
<head>

<script type="text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>

</head>

<body>
<p>Click the following button and see result</p>

<form>
<input type="button" value="Say Hello" />
</form>

</body>
</html>

2. onsubmit Event type


onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.

Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form
will be submitted, otherwise it will not submit the data.

Try the following example.

<html>
<head>

33
JavaScript

<script type="text/javascript">
function validation()
{

return either true or false


}
</script>

</head>
<body>

<form method="POST" action="[Link]" validate()">


.......
<input type="submit" value="Submit" />
</form>

</body>
</html>

3. onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the
following example.

<html>
<head>

<script type="text/javascript">

function over()
{
[Link] ("Mouse Over");
}

function out()
{
[Link] ("Mouse Out");
}

</script>

34
JavaScript

</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>

<div >
<h2> This is inside the division </h2>
</div>

</body>
</html>

Types of Dialog Boxes in JavaScript


JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise an alert, or to get confirmation on any input or to have a kind of input from the users.
Here we will discuss each dialog box one by one.
1. Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example, if one
input field requires to enter some text but the user does not provide any input, then as a part
of validation, you can use an alert box to give a warning message.

Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.

Example
<html>
<head>

<script type="text/javascript">
<!--
function Warn()
{
alert ("This is a warning message!");

}
</script>

</head>
<body>
<p>Click the following button to see the result: </p>

35
JavaScript

<form>
<input type="button" value="Click Me" />
</form>

</body>
</html>
Output

2. Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays a
dialog box with two buttons: Cancel.

If the user clicks on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box
as follows.

Example
<html>
<head>

<script type="text/javascript">
function getConfirmation()
{

36
JavaScript

var retVal = confirm("Do you want to continue ?");


if( retVal == true )
{
[Link] ("User wants to continue!");
return true;
}
Else
{
[Link] ("User does not want to continue!");
return false;
}
}
</script>

</head>
<body>
<p>Click the following button to see the result: </p>

<form>
<input type="button" value="Click Me" />
</form>

</body>
</html>

Output

3. Prompt Dialog Box

37
JavaScript

The prompt dialog box is very useful when you want to pop-up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click
OK.

This dialog box is displayed using a method called prompt() which takes two parameters: (i) a
label which you want to display in the text box and (ii) a default string to display in the text
box.

This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt()returns null.

Example
The following example shows how to use a prompt dialog box −

<html>
<head>

<script type="text/javascript">
<!--
function getValue()
{
var retVal = prompt("Enter your name : ", "your name here");
[Link]("You have entered : " + retVal);
}
</script>

</head>

<body>
<p>Click the following button to see the result: </p>

<form>
<input type="button" value="Click Me" />
</form>

</body>
</html>

38
JavaScript

Output

39
JavaScript

JavaScript - Errors & Exceptions Handling


Here are three types of errors in programming:
(a) Syntax Errors,
(b) Runtime Errors, and
(c) Logical Errors.

Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript

Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).

Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the
result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic
that drives your script and you do not get the result you expected.

Exception Handling

The try...catch...finally Statement

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally
construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch
JavaScript syntax errors.
Here is the try...catch...finally block syntax –

<script type = "text/javascript">

try

// Code to run

40
JavaScript

}
catch ( e )
{

// Code to run if an exception occurs

}
finally
{
// Code that is always executed regardless of
// an exception occurring
}
</script>

JavaScript querySelector
The querySelector is a JavaScript method that plays a vital role in the searching of elements. In this
section, we will understand and discuss the querySelector () method, its use and also look over an
example to understand the concept of the querySelector () method practically.

Introducing JavaScript querySelector () method


An element interface method that enables us to search and return the first element within the document.
It finds that element that matches with any of the specified CSS selectors or group of selectors. However,
if no matching element is found, it returns null. The querySelector () method is the method of the
Document interface only. A document interface is an interface that describes the common methods as
well as the properties for any html, XML, or any other kind of document.

How does the querySelector () method perform the searching


We know that there are different types of searches that can be used for searching elements. However, the
querySelector () method uses depth-first pre-order traversal of the nodes of the document. In it, the
traversal starts with the first element in the document's markup and then traverse through the sequential
nodes by order of the number of child nodes.

Syntax

The querySelector () method is a method of document interface and so it has such syntax. It has one
parameter, 'selectors', which is a DOM string and has one or more valid CSS selectors.

Return Type It may return 'null' if no match is found, and if the first element matches the specified CSS
selectors (if any), it will return that element. However, if there is not any valid CSS selector, it will throw a
'Syntax Error' exception.

41
JavaScript

So, we will now implement an example under which we will cover a CSS selector and retain its first
element value by using the querySelector () method.

Implementing querySelector () Example


Below is an example code that will make us understand the working of querySelector () method:

The output of the above code is shown below:

Code Explanation

o The above code is a combination of html and JavaScript.


o We have implemented different CSS selectors in the code.
o In the JavaScript section, we have used a querySelector () and invoked an element selector of CSS.
o So, the querySelector () method now moves to the code for traversing it using the Depth-first pre-
order method and returns the first element selector as it finds it.
In this way, the querySelector () method gets executed, and you can also try and use the querySelector ()
method for other CSS selectors also.

42
JavaScript

Let's also see and use the same example for other CSS selectors also. Just replace the element selector
code with these selector codes described below:

Few CSS Selectors

Class Selector

We need to use the (.) operator with the class name for finding the class first element. In the output, you
will see that the querySelector () searches from the starting of the code and the search get completed on
the h1 class element and so its return has a specified value as you can see below:

ID Selector

Use (#) for using the ID selector of CSS.

The output will be as shown below:

Attribute Selector

43
JavaScript

The output of the above code will be 'null' because, in our code, we have not used any such attribute as
shown below:

So, there are various CSS selectors and can be used if one has complete knowledge and understanding of
the CSS selectors and its types.

JavaScript querySelectorAll () Method

The querySelector () method of JavaScript is used for selecting only the first element from the code. But
what in case we want to retain more than one CSS selector value from the code. So, for such a case, we
use another method of the Document interface, which is known as the querySelectorAll () method. The
querySelectorAll () method is a method that is used to return all the matching values of the specified CSS
selector or group of a CSS selector.

Syntax

In the syntax, it contains selectors as an argument which holds one or more selectors with which we may
match the values.

Return
If the matching list or selector is found, it will return the specified value of those. Else it will return
an empty nodeList if no match is found.
Also, in case the specified CSS selectors have CSS pseudo-element, it will return an empty list.

Syntax Error
If there is a syntax error, it will return a syntax error exception that the specified selector's string is not
valid.

Example
Below is the same example we have used for explaining the querySelector () method, let's look at the
same example to understand the difference between both the methods:

44
JavaScript

Now, you can see the difference between the code that in the first example, we used the querySelector ()
method and it outputted only the first matching selector value. But, when you observe the output of this
second example, you will see that it has returned all the matching values of the specified selectors or
group of selectors. The output of the above code is shown below:

Code Explanation

o The above code is a combination of html and JavaScript.


o We have implemented different CSS selectors in the code.
o In the JavaScript section, we have used a querySelectorAll () method and invoked an element
selector of CSS.
o So, the querySelectorAll () method now moves to the code for traversing it using the Depth-first
pre-order method and returns all the matching element values that are specified as
querySlectorAll () method parameters.
So, in the same way, we can use the querySelectorAll () method for the various other types of CSS
selectors also, and it will return all the matching values of the selectors which are specified as its
argument. In order to implement the method, replace the querySelector () method with querySelectorAll

45
JavaScript

() method for various selectors, and the method will find the match and will return atleast one matching
value of the specified element.

DOM Manipulation

What is the DOM?


The Document Object Model (DOM) is a programming interface for web documents. It represents the
structure of a document as a tree of objects, where each object corresponds to a part of the document,
such as elements, attributes, and text. JavaScript can manipulate this tree structure, allowing developers
to dynamically alter the content and appearance of a webpage.

How to access DOM elements


To manipulate the DOM, we need to access its elements. This is commonly done using
the document object, which represents the entire HTML document. Let's look at a simple example:

In the code snippet above, we use getElementById, getElementsByClassName,


and getElementsByTagName to retrieve specific elements. The returned values can then be stored in
variables for further manipulation.
How to modify element content
Once we have access to an element, we can modify its content using the innerHTML property:

In the example above, we changed the content of the headerElement to New Header Text. This is a simple
yet powerful way to update the text within an element.

46
JavaScript

Common DOM Methods:


 [Link](id): Selects an element by its id.
 [Link](selector): Selects the first matching element using a CSS selector.
 [Link](selector): Selects all matching elements.
 [Link]: Gets or sets the text content of an element.
 [Link]: Gets or sets the HTML content inside an element.
 [Link]: Modifies the CSS properties of an element.
 [Link](event, function): Adds an event listener to an element.
 [Link](): Removes an element from the DOM.

Console in JavaScript
The console object is a useful tool for logging, debugging, and interacting with the browser's developer
tools (DevTools). It provides methods for outputting messages, measuring performance, and inspecting
values, which helps developers during the development process.
Here are detailed explanations of some commonly used methods within the console object:

1. [Link]()
The most commonly used method, [Link](), outputs general information, variables, or objects to the
console.
Usage: Display any message or value, like strings, numbers, arrays, or objects.
Example:
[Link]("Hello, world!"); // Outputs: Hello, world!
let name = "Alice";
[Link](name); // Outputs: Alice
// Logging multiple values
let age = 25;
[Link]("Name:", name, "Age:", age); // Outputs: Name: Alice Age: 25

47
JavaScript

2. [Link]()
The [Link]() method is used to output error messages. It usually highlights the error in the console
with a red color (depending on the browser), making it stand out.
Usage: Display error messages to the console for better visibility.
Example:
[Link]("This is an error message!"); // Outputs a red error message

3. [Link]()
The [Link]() method is used to output warning messages. Warnings are usually displayed in yellow
or orange in the DevTools console, making them stand out as less severe than errors but still important.
Usage: Display warning messages, often used for potential issues that should be looked into but aren't
errors.
Example:
[Link]("This is a warning!"); // Outputs a yellow warning message

4. [Link]()
The [Link]() method is similar to [Link](), but it is generally used for informational messages. It
provides the same output as [Link]() but can be used semantically to signify that the message is
meant to inform rather than just log general output.
Usage: Display informational messages, often for status updates or additional context.
Example:
[Link]("This is an info message."); // Outputs the message as informational

[Link]()
The [Link]() method displays tabular data in a neat, formatted table in the console. It's particularly
useful when logging arrays or objects with multiple properties.
Usage: Log arrays or objects in a table format for better readability.
Example:

48
JavaScript

6. [Link]() and [Link]()


[Link]() is used to group related log messages together in a collapsible manner. This can help
organize logs into nested groups, making it easier to trace and debug related messages.
Usage: Group related logs into collapsible sections.
[Link](): Ends the current group.

7. [Link]()
The [Link]() method logs the number of times it has been called with the same label. It can be
used for counting function calls or occurrences of certain events.
Usage: Track how many times a particular point in the code has been reached.
Example:
[Link]("Function Call");
[Link]("Function Call");
[Link]("Function Call");
Output: Function Call: 1
Function Call: 2
Function Call: 3
8. [Link]() and [Link]()
[Link]() and [Link]() are used to measure how long a piece of code takes to execute. You
can give them a label to identify multiple timers.
Usage: Measure execution time of a particular block of code.
Example:

49
JavaScript

[Link]("Timer1");
for (let i = 0; i < 1000000; i++) {} // Some heavy operation
[Link]("Timer1"); // Outputs: Timer1: <time>ms

Output:
Timer1: 12.34ms

9. [Link]()
The [Link]() method is used to log an error message if the given expression evaluates to false. If
the expression is true, nothing is logged.
Usage: Perform assertions to check conditions in your code, and only log messages if the condition fails.
Example:
let number = 5;
[Link](number > 10, "Number is not greater than 10");
// This will print: Assertion failed: Number is not greater than 10
[Link](number < 10, "Number is less than 10");
// This will not log anything because the assertion is true.

10. [Link]()
The [Link]() method outputs a stack trace to the console, which shows the call path that led to the
point where the trace was called.
Usage: Get a stack trace to trace function calls and find where an issue originated.
Example:
function level1() {
level2();
}

function level2() {
level3();
}

function level3() {
[Link](); // Outputs stack trace
}

level1();

Output:
Trace
at level3 ([Link])
at level2 ([Link])
at level1 ([Link])
at <anonymous> ([Link])
11. [Link]()

50
JavaScript

[Link] [Link]() method displays an interactive list of the properties of a specified JavaScript object.
It's particularly useful when you want to inspect an object in a more structured way than with
[Link]().
Usage: Explore the properties of an object, including non-enumerable ones.
Example:
const person = { name: "Alice", age: 25, greet() { [Link]("Hello"); } };
[Link](person); // Shows all properties of the person object

Arrow Functions in JavaScript


Arrow functions, introduced in ECMAScript 6 (ES6), offer a more concise syntax for writing functions. They
also have some key differences from regular functions, particularly in how they handle the this keyword.
Syntax of Arrow Functions
Arrow functions have a more compact syntax compared to regular function expressions.
Syntax:
const functionName = (param1, param2, ...) => expression;

this Binding in Arrow Functions


One of the most significant differences between regular functions and arrow functions is how they handle
the this keyword.

 In Regular Functions: The value of this is determined by how the function is called. It can refer to
the global object, the object calling the function, or be explicitly bound using call(), apply(), or
bind().
 In Arrow Functions: Arrow functions do not have their own this context. Instead, they inherit this
from the enclosing lexical scope (the context where the function is created).

Example with Regular Function:


function RegularFunction() {
[Link] = 42;
setTimeout(function() {
[Link]++; // `this` refers to the global object (or `undefined` in strict mode)
[Link]([Link]); // NaN or throws an error in strict mode
}, 1000);
}

Example with Arrow Function:


function ArrowFunction() {
[Link] = 42;
setTimeout(() => {
[Link]++; // `this` refers to the surrounding context (ArrowFunction instance)
[Link]([Link]); // 43
}, 1000);
}

51
JavaScript

Here, in the ArrowFunction, this correctly refers to the instance of ArrowFunction because arrow
functions inherit this from their surrounding scope.
Arrow Functions with Methods (Objects)
Arrow functions are often used in objects, but there is a caveat when using them for object methods:
since arrow functions don’t have their own this, they can't be used as methods that refer to the object's
own properties.
Example with Regular Method:
const person = {
name: "Alice",
greet() {
[Link](`Hello, my name is ${[Link]}`);
}
};
[Link](); // Outputs: Hello, my name is Alice

Example with Arrow Function (Problem with this):


const person = {
name: "Alice",
greet: () => {
[Link](`Hello, my name is ${[Link]}`); // `this` doesn't refer to `person`
}
};
[Link](); // Outputs: Hello, my name is undefined
or object methods, use regular function expressions instead of arrow functions.

Intervals in JavaScript
In JavaScript, intervals are used to repeatedly execute a function at specified time intervals. The most
common way to work with intervals is through the setInterval() method, which is part of the Web API.
1. setInterval()
The setInterval() method is used to execute a specified function repeatedly, with a fixed time delay
between each call.
Syntax:
const intervalId = setInterval(callback, delay, ...args);
 callback: The function to be executed.
 delay: The time, in milliseconds, to wait between each execution of the function (1000ms = 1
second).
 ...args (optional): Arguments to pass to the callback function when it is called.

Example 1: Basic Interval


let counter = 0;
const intervalId = setInterval(() => {
[Link]("Counter:", counter);
counter++;
}, 1000); // Executes every 1 second

52
JavaScript

In this example, the counter will be printed every second and incremented by 1 each time.

2. Stopping the Interval: clearInterval()


To stop an interval, you can use the clearInterval() method, passing the interval ID returned by
setInterval().
Syntax:
clearInterval(intervalId);
Example 2: Stopping an Interval
let counter = 0;
const intervalId = setInterval(() => {
[Link]("Counter:", counter);
counter++;
if (counter >= 5) {
clearInterval(intervalId); // Stops the interval after 5 executions
}
}, 1000);
In this example, the setInterval() function will execute every second, but it will stop automatically once
the counter reaches 5.

3. Using setInterval() with Arguments


If you want to pass additional arguments to the function being executed, you can do so using setInterval().
Example 3: Passing Arguments
function greet(name) {
[Link](`Hello, ${name}!`);
}
const intervalId = setInterval(greet, 2000, "Alice"); // Executes greet("Alice") every 2 seconds
In this case, the greet() function will be executed every 2 seconds with "Alice" passed as an argument.

[Link] Considerations
1. Minimum Delay:

 Browsers often have a minimum delay of around 4ms for setInterval(), even if you specify a smaller
value. This is done to prevent excessive CPU usage.
 If the interval delay is very small (like 1 or 2ms), you might not get the expected precision.

2. Execution Delay and Drift:

 If the callback function takes longer to execute than the interval delay, the next execution will be
delayed, causing drift.
 For example, if the function takes 1 second to execute but you set the interval to 1 second, the
function will actually execute every 2 seconds.

53
JavaScript

3. Timer Accuracy:

 setInterval() is not always 100% accurate. It depends on various factors like the system's
performance and whether the browser is busy doing other tasks.

[Link] to setInterval() - setTimeout()

You can also simulate intervals using setTimeout() by calling it recursively.

Simulating Interval with setTimeout():


Instead of using setInterval(), you can use setTimeout() to create a similar behavior with more control
over timing.
Example 4: Simulating Interval Using setTimeout()
let counter = 0;
function repeat() {
[Link]("Counter:", counter);
counter++;
if (counter < 5) {
setTimeout(repeat, 1000); // Schedule the next call in 1 second
}
}
setTimeout(repeat, 1000); // Starts the first call after 1 second
In this example, setTimeout() is used to recursively call the repeat() function after a 1-second delay,
simulating the behavior of setInterval(). This approach gives you more control over the interval execution.

[Link] Uses of setInterval()

Updating UI elements: You can use setInterval() to update certain elements on the page at regular
intervals, such as updating a clock or displaying live data.
setInterval(() => {
[Link]("clock").textContent = new Date().toLocaleTimeString();
}, 1000); // Updates the time every 1 second
Animation Loops: In animations, you can use setInterval() to move elements or change their properties at
regular intervals.
Polling data: You might use setInterval() to repeatedly check for new data from an API at regular
intervals.
setInterval(() => {
fetch("/api/data")
.then(response => [Link]())
.then(data => [Link](data));
}, 5000); // Polls for new data every 5 seconds

54
JavaScript

Local Storage in JavaScript


Local Storage is a web API provided by modern browsers that allows you to store data on the user's
device in the form of key-value pairs. It’s part of the Web Storage API, which also includes Session
Storage. Unlike Session Storage, Local Storage persists even after the browser window is closed, making it
ideal for storing data that should remain available across sessions.

What is Local Storage?

 Persistent storage: Data stored in Local Storage remains even after the browser or tab is closed
and reopened.
 Storage capacity: Typically, Local Storage allows around 5MB of data to be stored, but this can
vary by browser.
 Key-Value pairs: Local Storage stores data as key-value pairs, both of which are strings.
 No expiration: Data in Local Storage does not expire unless it is explicitly removed, unlike cookies,
which have expiration dates.

Common Operations with Local Storage


[Link] Data
To store data, you use the [Link]() method. This method accepts two arguments:

1. The key: A unique identifier for the data.


2. The value: The data to store (must be a string).

Syntax: [Link](key, value);

Example: Store a simple string

[Link]('username', 'Alice');
Example: Store a number (converted to string) [Link]('age', '25');
Example: Store an object (converted to string using [Link]())
const user = { name: 'Alice', age: 25 };
[Link]('user', [Link](user));

[Link] Data
To retrieve data, you use [Link](), which accepts the key and returns the value associated
with that key.
Syntax:
Example: Retrieve the stored usernamelet username = [Link]('username');
[Link](username); // Outputs: "Alice"

[Link] Data
You can remove specific items from Local Storage using [Link]().
Syntax:
[Link](key);

55
JavaScript

Clearing All Data

To remove all data stored in Local Storage, you can use [Link](). This will clear everything,
including all keys and values.

Syntax:
[Link]();
Example: Clear all data in Local Storage
[Link]();
Checking if Data Exists
To check if a key exists in Local Storage, you can use [Link](). If the item does not exist, it
will return null.
Example
let data = [Link]('nonexistentKey');
if (data === null) {
[Link]('Item not found.');
} else {
[Link]('Item found:', data);
}

Local Storage Limitations

[Link] Size: Most browsers limit Local Storage to around 5MB per domain.
[Link]-only Storage: Local Storage can only store strings. Non-string data (like arrays or objects) must be
serialized (using [Link]()) before storing and deserialized (using [Link]()) when retrieving.
[Link] Expiry Mechanism: Data in Local Storage does not have an expiration time, meaning you must
explicitly remove it when it's no longer needed

Security Considerations

 Sensitive Data: Local Storage is accessible from JavaScript running on the same domain. This
makes it vulnerable to cross-site scripting (XSS) attacks. Avoid storing sensitive data like
passwords or tokens directly in Local Storage.
 Limited security: Data stored in Local Storage is not encrypted, so any sensitive information stored
can be accessed by anyone who can view the browser’s storage (through Developer Tools).

Local Storage vs. Session Storage

 Local Storage:
o Data persists even after the browser is closed.
o Data is available for the entire session and across tabs/windows for the same origin.
 Session Storage:
o Data only persists for the duration of the page session (until the tab is closed).
o Data is isolated to the specific tab/window in which it was created.

56

You might also like