JavaScript UNIT II
UNIT – II
JavaScript Language Essentials
2.1 JavaScript Loops
JavaScript Loops are powerful tools for performing repetitive tasks efficiently. Loops in
JavaScript execute a block of code again and again while the condition is true.
For example, suppose we want to print “Hello World” 5 times. This can be done using JS
Loop easily. In Loop, the statement needs to be written only once and the loop will be
executed 5 times.
There are four types of loops in JavaScript.
for loop
while loop
do-while loop
for-in loop
1. For Loop
The JS for loop provides a brief way of writing the loop structure. The for loop contains
initialization, condition, and increment/decrement in one line thereby providing a shorter,
easy-to-debug structure of looping.
Syntax
for (initialization; testing condition; increment/decrement)
{
statement(s)
}
Initialization condition: It initializes the variable and mark the start of a for loop.
An already declared variable can be used or a variable can be declared, local to loop
only.
Test Condition: It is used for testing the exit condition of a for loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to
the execution of the loop statements.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 1
[Link]
JavaScript UNIT II
Statement execution: Once the condition is evaluated to be true, the statements in
the loop body are executed.
Increment/ Decrement: It is used for updating the variable for the next iteration.
Loop termination: When the condition becomes false, the loop terminates marking
the end of its life cycle.
Example:
// JavaScript program to illustrate for
loop let i;
// for loop begins when x = 2
// and runs till x <= 4
for (i = 1; i <= 5; i+
+) {
[Link]("Value of i: " + i);
Output
Value of i:
1 Value of
i: 2 Value
of i: 3
Value of i:
4
2. For-in Loop
JavaScript for-in loop is used to iterate over the properties of an object. The for-in loop iterates
only over those keys of an object which have their enumerable property set to “true”.
Syntax:
for(let variable_name in object_name)
{
// Statement
}
Example:
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 2
[Link]
JavaScript UNIT II
// JavaScript program to illustrate for-in loop
let myObj = { 1:"JavaScript", 2:"Web Technology", 3:"E-Commerse",
4:"GD" }; for (let key in myObj)
{
[Link](key, myObj[key]);
}
Output
1 JavaScript
2 Web Technology
3 E-Commerse
4 GD
3. For-of Loop
JavaScript for-of loop is used to iterate the iterable objects for example – array, object, set
and map. It directly iterate the value of the given iterable object and has more concise syntax
than for loop.
Syntax:
for(let variable_name of object_name)
{
// Statement
}
Example:
// JavaScript program to illustrate for-of loop
// Iterating over array
let letters = ["a", "b", "c", "d"];
[Link]("Iterating over array");
for(let letter of letters) {
[Link](letter); // a,b,c,d
}
// Iterating over
string let greet =
"Hello NIIT!";
[Link]("Iterating over string");
for(let character of greet) {
[Link](character); // H,e,l,l,o, ,N,I,I,T,!
}
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 3
[Link]
JavaScript UNIT II
4. While Loop
The JS while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as a
repeating if statement.
While loop starts with checking the condition. If it is evaluated to be true, then the
loop body statements are executed otherwise first statement following the loop is
executed. For this reason, it is also called the Entry control loop
Once the condition is evaluated to be true, the statements in the loop body are
executed. Normally the statements contain an updated value for the variable being
processed for the next iteration.
When the condition becomes false, the loop terminates which marks the end of its life
cycle.
Syntax
:
while(condition)
{
//Code to be executed
}
Example:
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript While Loop</title>
</head>
<body>
<script>
let i =
1;
while(i <= 5) {
[Link]("<p>The number is " + i +
"</p>"); i++;
}
</script>
</body>
Output:
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 4
[Link]
JavaScript UNIT II
5. Do-while Loop
The JS do-while loop is similar to the while loop with the only difference is that it
checks for the condition after executing the statements, and therefore is an example of
an Exit Control Loop. It executes loop content at least once event the condition is
false.
The do-while loop starts with the execution of the statement(s). There is no checking
of any condition for the first time.
After the execution of the statements and update of the variable value, the condition is
checked for a true or false value. If it is evaluated to be true, the next iteration of the
loop starts.
When the condition becomes false, the loop terminates which marks the end of its life
cycle.
It is important to note that the do-while loop will execute its statements at least once
before any condition is checked and therefore is an example of the exit control loop.
Syntax:
do {
// Code to be executed
}
while(condition);
Example:
<html lang="en">
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 5
[Link]
JavaScript UNIT II
<head>
<meta charset="utf-8">
<title>JavaScript Do-While Loop</title>
</head>
<body>
<script>
let i =
1; do {
[Link]("<p>The number is " + i +
"</p>"); i++;
}
while(i <= 5);
</script>
</body>
</html>
Output:
6. Difference between while and do-while loop
while do-while
Condition is checked first then statement(s) Statement(s) is executed at least once,
is executed. thereafter condition is checked.
It might occur statement(s) is executed zero
At least once the statement(s) is executed.
times, If condition is false.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 6
[Link]
JavaScript UNIT II
while do-while
No semicolon at the end of while. Semicolon at the end of while.
while(condition) while(condition);
If there is a single statement, brackets are
Brackets are always required.
not required.
Variable in condition is initialized before variable may be initialized before or within
the execution of loop. the loop.
while loop is entry controlled loop. do-while loop is exit controlled loop.
do{statement(s);
while(condition)
}
{ statement(s); }
while(condition);
2.2 Passing values to function
In javascript pass by value, the function is called by directly passing the value of the
variable as the argument. Therefore, even changing the argument inside the function
doesn’t affect the variable passed from outside the function.
It is important to note that in javascript, all function arguments are always passed by
value. That is, JavaScript copies the values of the passing variables into arguments
inside of the function.
Example:
function square(x)
{ x = x * x;
return x;
}
let y = 10;
let result = square(y);
[Link](result); // 100
[Link](y); // 10 -- no change
Example:
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 7
[Link]
JavaScript UNIT II
// program to add two numbers using a function
// declaring a function
function add(a, b) {
[Link](a + b);
}
// calling functions
add(20,30);
add(5,8);
2.3 Returning values from function
JavaScript return statement is used to return a particular value from the function.
The function will stop the execution when the return statement is called and return a
specific value.
The return statement should be the last statement of the function because the code
after the return statement won’t be accessible.
We can return any value i.e. Primitive value (Boolean, number and string, etc) or
object type value ( function, object, array, etc) by using the return statement.
Example:
function Product(a, b)
{
// Return the product of a and b
return a * b;
};
[Link](Product(6, 10));
Example:
//return multiple values by using the
object function Language() {
let first = 'HTML',
second = 'CSS',
Third =
'Javascript'
return {
first,
second
,
Third
};
}
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 8
[Link]
JavaScript UNIT II
[Link](first);
[Link](second);
[Link](Third);
2.4 Arrays
1. What is Array in JavaScript?
JavaScript Array is a data structure that allows you to store and organize multiple
values within a single variable.
It is a versatile and dynamic object. It can hold various data types, including
numbers, strings, objects, and even other arrays.
Arrays in JavaScript are zero-indexed i.e. the first element is accessed with an index
0, the second element with an index of 1, and so forth.
You can create JavaScript Arrays using the Array constructor or using the
shorthand array literal syntax, which employs square brackets.
Arrays can dynamically grow or shrink in size as elements are added or removed.
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
Suppose we need to record the age of 5 students. Instead of creating 5 separate
variables, we can simply create an array:
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 9
[Link]
JavaScript UNIT II
2. Basic Terminologies of JavaScript Array
Array: A data structure in JavaScript that allows you to store multiple values in a
single variable.
Array Element: Each value within an array is called an element. Elements are
accessed by their index.
Array Index: A numeric representation that indicates the position of an element in
the array. JavaScript arrays are zero-indexed, meaning the first element is at index
0.
Array Length: The number of elements in an array. It can be retrieved using the
length property.
3. Declaration of an Array
There are basically two ways to declare an array
i. Array Literal
ii. Array Constructor.
i. Creating an Array using Array Literal
Creating an array using array literal involves using square brackets [] to define
and initialize the array. This method is concise and widely preferred for its
simplicity. Syntax:
let arrayName = [value1, value2, ...];
Example:
// Creating an Empty
Array let names = [];
[Link](names);
// Creating an Array and Initializing with Values
let courses = ["Web Technology", "E-commerce", "JavaScript", "GD"];
[Link](courses);
Output:
[]
[ 'Web Technology', 'E-commerce', 'JavaScript', 'GD' ]
[Link]
JavaScript UNIT II
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 10
[Link]
JavaScript UNIT II
ii. Creating an Array using Array Constructor (JavaScript new Keyword)
The “Array Constructor” refers to a method of creating arrays by invoking the
Array constructor function. This approach allows for dynamic initialization and
can be used to create arrays with a specified length or elements.
Syntax:
let arrayName = new Array();
Example:
// Declaration of an empty array
// using Array
constructor let names =
new Array();
[Link](names);
// Creating and Initializing an array with values
let courses = new Array("Web Technology", "E-commerce",
"JavaScript", "GD");
[Link](courses);
// Initializing Array while
declaring let arr = new Array(3);
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
[Link](arr);
Output:
[]
[ 'Web Technology', 'E-commerce', 'JavaScript',
'GD' ] [ 10, 20, 30 ]
4. Basic Array Operation on Array
1. Accessing element of an array: Any element in the array can be accessed using the
index number. The index in the arrays starts with 0.
2. Accessing the First Element of an Array: The array indexing starts from 0, so we can
access first element of array using the index number.
3. Accessing the Last Element of an Array: We can access the last array element using
[[Link] – 1] index number.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 11
[Link]
JavaScript UNIT II
4. Modifying the Array Elements: Elements in an array can be modified by assigning a
new value to their corresponding index.
5. Adding Elements to the Array: Elements can be added to the array using methods like
push() and unshift().
Example:
// Declaration of an empty array
// using Array
constructor let names =
new Array();
[Link](names);
// Creating and Initializing an array with values
let courses = new Array("Web Techanolgy", "E-commerce",
"Javascript", "GD");
[Link](courses);
// Accessing First Array
Elements let firstItem =
courses[0];
[Link]("First Item: ", firstItem);
// Accessing Last Array Elements
let lastItem = courses[[Link] -
1]; [Link]("Last Item: ", lastItem);
//Modifying the Array Elements
courses[1]= "CSS";
[Link](courses);
// Add Element to the end of Array
[Link]("[Link]");
// Add Element to the beginning
[Link]("Web Development");
Output:
[]
[ 'Web Techanolgy', 'E-commerce', 'Javascript', 'GD'
] First Item: Web Techanolgy
Last Item: GD
[ 'Web Techanolgy', 'CSS', 'Javascript',
'GD' ] [
'Web Development',
'Web Techanolgy',
'CSS',
'Javascript',
'GD',
'[Link]'
]
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 12
[Link]
JavaScript UNIT II
6. Removing Elements from an Array: Remove elements using methods like
pop(), shift(), or splice().
// Creating an Array and Initializing with Values
let courses = ["Web Techanolgy", "E-commerce", "Javascript", "GD",
"[Link]"];
[Link]("Original Array: " + courses);
// Removes and returns the last
element let lastElement =
[Link]();
[Link]("After Removed the last elements: " + courses);
// Removes and returns the first
element let firstElement =
[Link]();
[Link]("After Removed the First elements: " + courses);
// Removes 2 elements starting from index
1 [Link](1, 2);
Output:
Original Array: Web Techanolgy,E-
commerce,Javascript,GD,[Link] After Removed the last
elements: Web Techanolgy,E-commerce,Javascript,GD
After Removed the First elements: E-commerce,Javascript,GD
After Removed 2 elements starting from index 1: E-commerce
7. Array length: Get the length of an array using the length property.
8. Increase and Decrease the Array Length: We can increase and decrease the array
length using the JavaScript length property.
Example:
// Creating an Array and Initializing with Values
let courses = ["Web Techanolgy", "E-commerce", "Javascript",
"GD", "[Link]"];
let len = [Link];
[Link]("Array Length: " +
len);
// Increase the array length to 7
[Link] = 7;
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 13
[Link]
JavaScript UNIT II
[Link]("Array After Increase the Length: ", courses);
// Decrease the array length to 2
[Link] = 2;
[Link]("Array After Decrease the Length: ", courses);
Output:
Array Length: 5
Array After Increase the
Length: [ 'Web Techanolgy',
'E-
commerce',
'Javascript'
, 'GD',
'[Link]',
<2 empty items>
]
Array After Decrease the Length: [ 'Web Techanolgy', 'E-
commerce' ] Web Techanolgy
E-commerce
9. Iterating Through Array Elements: We can iterate array and access array elements
using for and forEach loop.
Example:
// Creating an Array and Initializing with Values
let courses = ["Web Techanolgy", "E-commerce", "Javascript",
"GD"];
// Iterating through for loop
[Link]("Iterating using for
loop:"); for (let i = 0; i <
[Link]; i++) {
[Link](courses[i])
}
// Iterating through forEach loop
[Link]("Iterating using forEach loop:");
[Link](function myfunc(elements) {
[Link](elements);
Output:
Iterating using for loop
Web Techanolgy
E-commerce
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 14
[Link]
JavaScript UNIT II
Javascrip
t GD
Iterating using forEach
loop Web Techanolgy
E-commerce
Javascrip
t GD
10. Array Concatenation: Combine two or more arrays using the concat() method. It returns
new array containing joined arrays elements.
// Creating an Array and Initializing with Values
let courses = ["Web Techanolgy", "E-commerce", "Javascript",
"GD"]; let otherCourses = ["[Link]", "React"];
// Concatenate both arrays
let concateArray = [Link](otherCourses);
[Link]("Concatenated Array: ", concateArray);
Output:
Concatenated Array:
[ 'Web
Techanolgy',
'E-
commerce',
'Javascript'
, 'GD',
'[Link]',
'React'
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 15
[Link]
JavaScript UNIT II
5. Array Methods
In JavaScript, there are various methods available that make it easier to perform useful
operations with arrays. Some commonly used array methods in JavaScript are:
Methods Description
concat() It returns a new array object that contains two or more merged
arrays.
copywithin() It copies the part of the given array with its own elements and
returns the modified array.
entries() It creates an iterator object and a loop that iterates over each
key/value pair.
every() It determines whether all the elements of an array are
satisfying the provided function conditions.
fill() It fills elements into an array with static values.
from() It creates a new array carrying the exact copy of another array
element.
find() It returns the value of the first element in the given array that
satisfies the specified condition.
findIndex() It returns the index value of the first element in the given
array that satisfies the specified condition.
forEach() It invokes the provided function once for each element of an
array.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 16
[Link]
JavaScript UNIT II
indexOf() It searches the specified element in the given array and
returns the index of the first match.
isArray() It tests if the passed value is an array.
join() It joins the elements of an array as a string.
keys() It creates an iterator object that contains only the keys of the
array, then loops through these keys.
lastIndexOf() It searches the specified element in the given array and
returns the index of the last match.
map() It calls the specified function for every array element and
returns the new array
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.
reverse() It reverses the elements of given array.
reduceRight( It executes a provided function for each value from right to
)
left and reduces the array to a single value.
some() It determines if any element of the array passes the test
of the implemented function.
shift() It removes and returns the first element of an array.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 17
[Link]
JavaScript UNIT II
slice() It returns a new array containing the copy of the part of the
given array.
sort() It returns the element of the given array in a sorted order.
splice() It add/remove elements to/from the given array.
toString() It converts the elements of a specified array into string form,
without affecting the original array.
unshift() It adds one or more elements in the beginning of the given
array.
values() It creates a new iterator object carrying values for each index
in the array.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 18
[Link]