0% found this document useful (0 votes)
14 views50 pages

CM Java Script Ver 9.0

Uploaded by

mt
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)
14 views50 pages

CM Java Script Ver 9.0

Uploaded by

mt
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

Chapter 1: JavaScript Fundamentals

1.1 Introduction to JavaScript


1.2 History of JavaScript
1.3 Applications of Java Script
1.4 Variables
1.5 Data Types
1.6 Operators
1.7 Functions
Chapter 2: Control Structures and Loops
2.1 Conditional Statements
2.2 Loops
Chapter 3: Advanced Functions
3.1 Higher-Order Functions
3.2 Closures
3.3 Callbacks and Promises
Chapter 4: Asynchronous JavaScript
4.1 Async/Await
4.3 Fetch API
Chapter 5: Working with Data
5.1 JSON
5.2 Local Storage and IndexedDB
Chapter 6: DOM Manipulation
6.1 Selecting and Modifying DOM Elements
6.2 Event Handling
Chapter 7: Object-Oriented JavaScript
7.1 Prototypes and Inheritance
7.2 ES6 Classes
Chapter 8: JavaScript ES6+ Features
8.1 Destructuring and Spread Operator
8.2 Template Literals and Modules
Chapter 9: Debugging and Testing
9.1 Debugging Techniques
9.2 Testing JavaScript
Chapter 1: JavaScript Fundamentals
1.1 Introduction to JavaScript
JavaScript is a light-weight, cross-platform, single-threaded, interpreted
programming language. It is also known as the scripting language for
webpages.
Javascript can be used for the development of web pages, and also for non-
browser environments.
JavaScript is a weakly typed language (dynamically typed).
JavaScript can be used for Client-side developments as well as Server-side
developments.
 Client-side: It supplies objects to control a browser and its Document
Object Model (DOM). Like if client-side extensions allow an application to
place elements on an HTML form and respond to user events such
as mouse clicks, form input, and page navigation.
 Server-side: The server-side work involves things like communicating with
database, manipulating files and generating response.
1.2 History of JavaScript
JavaScript was first implemented in Netscape Navigator. Microsoft adopted it
for Internet Explorer.
JavaScript was used to create a variety of web applications, including online
games, dynamic menus, and form validation.
Today, JavaScript is one of the most popular programming languages, used by
about 95% of websites. It is not only crucial for web development but also for
creating server-side applications, desktop and mobile apps, and even
programming robots and hardware.
1.3 Applications of Java Script
Web Development: Adding interactivity and behavior to static sites
Web Applications: With technology, browsers have improved to the extent that
a language was required to create robust web applications. When we explore a
map in Google Maps then we only need to click and drag the mouse. All
detailed view is just a click away, and this is possible because of JavaScript. It
uses Application Programming Interfaces (APIs) that provide extra power to
the code. The Electron and React are helpful in this department.
Server Applications: With the help of [Link], JavaScript made its way from
client to server and [Link] is the most powerful on the server side.
Games: JavaScript also helps in creating games for leisure. The combination of
JavaScript and HTML 5 makes JavaScript popular in game development.
Art: Artists and designers can create whatever they want using JavaScript to
draw on HTML 5 canvas, and make the sound more effective.
Machine Learning: This JavaScript [Link] library can be used in web
development by using machine learning.
Mobile Applications: JavaScript can also be used to build an application for
non-web contexts.
1.4 Variables
Variables are used to store data in JavaScript. Variables are used to store
reusable values.
JavaScript variables must have unique names. These names are called
Identifiers.
JavaScript variables must have unique names. These names are called
Identifiers.
Basic rules to declare a variable in JavaScript:
 These are case-sensitive

 Can only begin with a letter, underscore (_) or $ symbol

 It can contain letters, numbers, underscore, or $ symbol

 A variable name cannot be a reserved keyword.

JavaScript is a dynamically typed language so the type of variables is decided


at runtime. Therefore, there is no need to explicitly define the type of a
variable. We can declare variables in JavaScript in three ways:
 JavaScript var keyword

 JavaScript let keyword

 JavaScript const keyword

Note: In JavaScript, variables can be declared automatically.


Syntax
// Declaration using var
var geek = "Hello Geek"

// Declaration using let


let $ = "Welcome"

// Declaration using const


const _example = "Gfg"
Example 1:
In this example, we will declare variables using var.
var a = "Hello Geeks";
var b = 10;
var c = 12;
var d = b + c;

[Link](a);
[Link](b);
[Link](c);
[Link](d);
Output
Hello Geeks
10
12
22
Example 2:
In this example, we will declare variables using let.
let a = "Hello learners"
let b = "joining";
let c = " 12";
let d = b + c;

[Link](a);
[Link](b);
[Link](c);
[Link](d);
Output
Hello learners
joining
12
joining 12
Example 3:
In this example, we will declare the variable using the const keyword.
const a = "Hello learners"
[Link](a);
const b = 400;
[Link](b);
const c = "12";
[Link](c);
// Can not change a value for a constant
c = "new"
[Link](c)
Output:

Example 4:
In this example, we are trying to access the block scoped variables outside the
block that is why we are getting error.
{
let a = 2;
var b = 4;
const c = "Hello";
[Link](a);
[Link](b);
[Link](c);
}
[Link](b);
[Link](c);
[Link](a);
Output:

1.5 Data Types


JavaScript uses different types of data to store various kinds of information, like
numbers, text, and complex structures. Each type helps JavaScript understand
what kind of data it is working with and how to process it. Knowing these data
types is essential for creating programs that function correctly and handle data
properly.
These two are the data types of the Javascript.
 Primitive Data Type

 Non-Primitive Data Types

1.5.1 Primitive Data Type


The predefined data types provided by JavaScript language are
known as primitive data types. Primitive data types are also
known as in-built data types.
Type Description

JavaScript numbers are always stored in double-precision 64-bit binary


Number
format.

JavaScript Strings are made up of a list of characters, essentially an array


String
of characters.

Boolean Represents a logical entity and can have two values: true or false.

Null This type has only one value: null.

Undefine
A variable that has not been assigned a value is undefined.
d

BigInt is a built-in object providing a way to represent


BigInt
whole numbers larger than 253-1.
Examples
1. Number
The Number data type represents both integer and floating-point numbers.
The Number data type contains both integer and floating-point numbers.
JavaScript does not distinguish between integers and floats. Some special
numbers in JavaScript are: Infinity, -Infinity, and NaN. The NaN denotes a
computational error.
let n1 = 2;
[Link](n1)
let n2 = 1.3;
[Link](n2)
let n3 = Infinity;
[Link](n3)
let n4 = 'something here too'/2;
[Link](n4)
Output:
2
1.3
Infinity
NaN
2. String
A String in JavaScript is a series of characters that are surrounded by quotes.
There are three types of quotes in Javascript, which are:
let s = "Hello There";
[Link](s);
let s1 = 'Single quotes work fine';
[Link](s1);
let s2 = `can embed ${s}`;
[Link](s2);
Output
Hello There
3. Boolean
The boolean type has only two values i.e. true and false.
let b1 = true;
[Link](b1);
let b2 = false;
[Link](b2);
Output
true
false
4. Null
The special null value does not belong to any of the default data types. It forms
a separate type of its own which contains only the null value.
let age = null;
[Link](age)
Output
null
5. Undefined
A variable that has been declared but not initialized with a value is
automatically assigned the undefined value. It means the variable exists, but it
has no value assigned to it.
let a;
[Link](a);
Output
undefined
6. BigInt (Introduced in ES2020)
BigInt is a built-in object that provides a way to represent whole numbers
greater than 253. The largest number that JavaScript can reliably represent
with the Number primitive is 253, which is represented by the
MAX_SAFE_INTEGER constant.
let b = BigInt("0b1010101001010101001111111111111111");
[Link](b);
Output
11430854655n
1.5.2 Non-Primitive Data Types
The data types that are derived from primitive data types are known as non-
primitive data types. It is also known as derived data types or reference data
types.
 Object: It is the most important data type and forms the building blocks for
modern JavaScript.
 Arrays: An Array is a special kind of object used to store an ordered
collection of values, which can be of any data type.
Examples
1. Object
JavaScript objects are fundamental data structures used to store collections of
data. They consist of key-value pairs and can be created using curly braces {} or
the new keyword. Understanding objects is crucial, as everything in JavaScript
is essentially an object.
Object Creation
Using the object constructor syntax
let o = new Object();
Using the object literal syntax
let o = {};
2. Arrays
An Array is a special kind of object used to store an ordered collection of
values, which can be of any data type.
let a = [1, 2, 3, 4, 5];
[Link](a);
let a2 = [1, "two", { name: "Object" }, [3, 4, 5]];
[Link](a2);
Output
[1, 2, 3, 4, 5]
[1, "two", { name: "Object" }, [3, 4, 5]]
1.6 Operators
JavaScript Operators are symbols used to perform specific mathematical,
comparison, assignment, and logical computations on operands. They are
fundamental elements in JavaScript programming, allowing developers to
manipulate data and control program flow efficiently.
Various types of operators supported by JavaScript are the following.
1.6.1 JavaScript Arithmetic Operators
JavaScript Arithmetic Operators perform arithmetic operations: addition (+),
subtraction (-), multiplication (*), division (/), modulus (%), and exponentiation
(**).
Name Description Syntax

Addition ‘+’ operator performs


addition on two operands. This ‘+’ Y = “Geeks” + “for” + “Geeks”
Addition (+)
operator can also be used to gives Y = “GeeksforGeeks” Y
concatenate (add) strings.

Subtraction ‘-‘ operator performs


Subtraction (-) Y = 5 – 3 gives Y = 2
subtraction on two operands.

Multiplication Multiplication ‘*’ operator performs


Y = 5 * 5 gives Y = 25
(*) multiplication on two operands.

Division ‘/’ operator performs


Division (/) division on two operands (divide the Y = 5 / 5 gives Y = 1
numerator by the denominator).

Modulus ‘%’ operator gives a A % B means remainder (A/B)


Modulus (%)
remainder of an integer division. Y = 5 % 4 gives Y = 1

Exponentiation ‘**’ operator give the


Exponentiatio
power of the first operator raised to Y = 5 ** 3 gives Y = 125
n (**)
the second operator.

Increment ‘+ +’ operator increases an let A = 10 and Y = A + + then A


Increment(++)
integer value by one. = 11, Y=10

Decrement ‘- -‘ operator decreases let A = 10 and Y = A – – then A


Decrement (–)
an integer value by one. = 9, Y=10

Negation ‘-‘ operator gives the -a means a is a negative


Negation (-)
negation of an operand. number

1.6.2 JavaScript Assignment Operators


The assignment operation evaluates the assigned value. Chaining the
assignment operator is possible in order to assign a single value to multiple
variables
Name Description Syntax

This operator assigns the right If A = 10 and Y = A then


Assignment (=)
operand value to the left operand. Y = 10

Sums up left and right operand values


Addition
and then assigns the result to the left Y += 1 gives Y = Y + 1
Assignment (+=)
operand.

It subtracts the right-side value from


Subtraction
the left side value and then assigns Y -= 1 gives Y = Y – 1
Assignment (-=)
the result to the left operand.

It multiplies a variable by the value of


Multiplication Y *= A is equivalent to Y
the right operand and assigns the
Assignment (*=) =Y*A
result to the variable.

It divides a variable by the value of


Division Assignment Y /= A is equivalent to Y
the right operand and assigns the
(/=) =Y/A
result to the variable.

Modules/ It divides a variable by the value of


Y %= A is equivalent to
Remainder the right operand and assigns the
Y=Y%A
Assignment (%=) remainder to the variable.

Exponentiation This raises the value of a variable to Y **= A is equivalent to


Assignment (**=) the power of the right operand. Y=Y ** A

It moves the specified amount of bits


Left Shift Y <<= A is equivalent to
to the left and assigns the result to
Assignment (<<=) Y=Y << A
the variable.

It moves the specified amount of bits


Right Shift Y >>= A is equivalent to
to the right and assigns the result to
Assignment (>>=) Y = Y >> A
the variable.

Bitwise AND : It does a bitwise AND operation on Y &= b is equivalent to


the operand, and assigns the result to
Assignment (&=) Y=Y&A
the variable.

It does a bitwise OR operation on the


Bitwise OR Y |= A is equivalent to
operand, and assigns the result to the
Assignment (|=) Y= Y | b
variable.

It does a bitwise XOR operation on


Bitwise XOR Y ^= A is equivalent to
the operand, and assigns the result to
Assignment (^=) Y= Y ^ A
the variable.

1.6.3 JavaScript Comparison Operators


Comparison operators are mainly used to perform the logical operations that
determine the equality or difference between the values.

Name Description Syntax

Compares the equality of two


Y = 5 and X = 6 Y = = X is
Equality (==) operands. If equal then the
false.
condition is true otherwise false.

Compares the equality of two


operands with type. If both value Y = 5 and X = ‘5’ Y = = = X is
Strict equality (===)
and type are equal then the false.
condition is true otherwise false.

Compares inequality of two


let X = 10 then X ! = 11 is
Inequality (!=) operands. True if operands are not
true.
equal.

Compares the inequality of two


Strict inequality (! operands with type. If both value let X = 10 then X ! == ’10’ is
==) and type are equal then the true.
condition is true otherwise false.

Greater than (>) This operator checks whether the let X = 10 then X > 11 is
left side value is greater than the false.
right side value. If yes then it
returns true otherwise it returns
false.

This operator checks whether the


left side value is less than the right let X = 10 then X < 11 is
Less than (<)
side value. If yes then it returns true.
true otherwise it returns false.

This operator checks whether the


left side operand is greater than or
Greater than or let X = 10 then X > = 11 is
equal to the right-side operand. If
Equal to (>=) false.
yes then it returns true otherwise
it returns false.

This operator checks whether the


left side operand value is less than
Less than or Equal let X = 10 then X < = 10 is
or equal to the right-side operand
to (<= ) true.
value. If yes then it returns true
otherwise it returns false.

1.6.4 JavaScript Logical Operators


JavaScript Logical Operators perform logical operations: AND (&&), OR (||), and
NOT (!), evaluating expressions and returning boolean values.

Name Description Syntax

It checks whether two operands


are non-zero (0, false, undefined,
Logical AND (&&) null, or “” are considered as zero), Y = 5 and X = 6 Y && X is 6.
if yes then return the last operand
when evaluating from left to right

It checks whether two operands


are non-zero (0, false, undefined,
Logical OR (||) null, or “” is considered as zero), if Y = 5 and X = 0 Y || X is 5.
yes then return the first operand
when evaluating from left to right.

Logical NOT (!) It reverses the boolean result of Y = 5 and X = 0 !(Y || X) is


the operand (or condition). false.

1.6.5 JavaScript Bitwise Operators


The bitwise operator in JavaScript is used to convert the number to a 32-bit
binary number and perform the bitwise operation. The number is converted
back to the 64-bit number after the result.

Name Description Syntax

The operator returns true only if


Bitwise AND (&) A = 6, B=1 A&B = 0
both the operands are true

The operator returns true even


Bitwise OR (|) A = 6, B=1 A|B = 7
if one of the operands is true

The operator returns true if


Bitwise XOR (^) A = 6, B=1 A^B = 7
both operators are distinct

This operator is used to invert


Bitwise NOT (~) the boolean value of the A = 6 ~A = -7
operand

In these two operators are used


where the first operand is the
Bitwise Left Shift
number and the second A = 6, B=1 A<<B = 12
(<<)
operand is the number of bits
to shift to the left.

In these two operators are used


where the first operand is the
Bitwise Right Shift
number and the second A = 6, B=1 A>>B = 3
(>>)
operand is the number of bits
to shift to the right.

It is same as a bitwise right shift


Zero Fill Right Shift
the only difference is that A = 6, B=1 A>>>B = 3
(>>>)
overflowing bits are discarded.
1.6.6 JavaScript Ternary Operators
The ternary operator has three operands. It is the simplified operator of if/else.

Name Description Syntax

Ternary Operator It is like the short form of the Y = ? A : B If the condition is true
(?:) if-else condition. then Y = A otherwise Y = B

1.6.7 JavaScript Comma Operators


Comma Operator (,) mainly evaluates its operands from left to right
sequentially and returns the value of the rightmost operand.

Name Description Syntax

When a comma operator is placed


in an expression, it executes each Expression1, Expression2,
comma operator (,)
expression and returns the Expression3, …so on
rightmost expression.

1.6.8 JavaScript Unary Operators


A unary operation is an operation with only one operand.

Name Description Syntax

It returns the operand type, The


possible types that exist in
JavaScript typeof javascript are undefined, Object, typeof variable
boolean, number, string, symbol,
and function.

delete object
This operator is more specifically // or
Delete used to delete JavaScript object delete [Link]
properties. // or
delete object[‘property’]
1.6.9 JavaScript Relational Operators
JavaScript Relational operators are used to compare its operands and
determine the relationship between them. They return a Boolean value (true
or false) based on the comparison result.

Name Description Syntax

The in operator returns true if the


propNameOrNumber in
in specified property is in the specified
objectName
object.

The instanceof operator returns true if


instanceo objectName instanceof
the specified object is of the specified
f objectType
object type.

1.6.10 JavaScript String Operators


JavaScript String Operators include concatenation (+) and concatenation
assignment (+=), used to join strings or combine strings with other data types.

Name Description Syntax

It concatenates two string values


concatenation
together, returning another string that is str1 + str2
operator (+)
the union of the two operand strings.

1.7 Functions
1.7.1 Overview
A function in JavaScript is a reusable block of code that performs a specific task.
You define it once, and then you can run (or call) it whenever you need that
task done in your program.
Syntax: The basic syntax to create a function in JavaScript is shown below.
function functionName(Parameter1, Parameter2, ...)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function,
separated by the name of the function and parameters within parenthesis. The
part of the function inside the curly braces {} is the body of the function.

1.7.2 Features
 Functions can be used multiple times, reducing redundancy.
 Break down complex problems into manageable pieces.
 Manage complexity by hiding implementation details.
 Can call themselves to solve problems recursively.
1.7.3 Function Invocation
The function code you have written will be executed whenever it is called.
 Triggered by an event (e.g., a button clicks by a user).
 When explicitly called from JavaScript code.
 Automatically executed, such as in self-invoking functions.
1.7.4 Function Definition
A function definition is sometimes also termed a function declaration or
function statement. Below are the rules for creating a function in JavaScript:
 Every function should begin with the keyword function followed by,
 A user-defined function name that should be unique,
 A list of parameters enclosed within parentheses and separated by commas,
 A list of statements composing the body of the function enclosed within
curly braces {}.
Example:
This example shows a basic declaration of a function in javascript.
function calcAddition(number1, number2) {
return number1 + number2;
}
[Link](calcAddition(6,9));

Output:
15
In the above example, we have created a function named calcAddition,
 This function accepts two numbers as parameters and returns the addition
of these two numbers.
 Accessing the function with just the function name without () will return the
function object instead of the function result.
There are three ways of writing a function in JavaScript:

1.7.5 Function Declaration


It declares a function with a function keyword. The function declaration must
have a function name.
Syntax:
function geeksforGeeks(paramA, paramB) {
// Set of statements
}

1.7.6 Function Expression


It is similar to a function declaration without the function name. Function
expressions can be stored in a variable assignment.
Syntax:
let geeksforGeeks= function(paramA, paramB) {
// Set of statements
}
Example: This example explains the usage of the Function expression.
const square = function (number) {
return number * number;
};
const x = square(4); // x gets the value 16
[Link](x);
Output
16
1.7.7 Functions as Variable Values
Functions can be used the same way as you use variables.
Example:
// Function to convert Fahrenheit to Celsius
function toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}

// Using the function to convert temperature


let temperatureInFahrenheit = 77;
let temperatureInCelsius = toCelsius(temperatureInFahrenheit);
let text = "The temperature is " + temperatureInCelsius + " Celsius";

1.7.8 Arrow Function


Arrow Function is one of the most used and efficient methods to create a
function in JavaScript because of its comparatively easy implementation. It is a
simplified as well as a more compact version of a regular or normal function
expression or syntax.

Syntax:
let function_name = (argument1, argument2 ,..) => expression

Example:
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = [Link](function (s) {
return [Link];
});
[Link]("Normal way ", a2); // [8, 6, 7, 9]
const a3 = [Link]((s) => [Link]);
[Link]("Using Arrow Function ", a3);
Output:
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
1.7.9 Function Parameters
Parameters are additional information (optional) passed to a function. The
parameters are passed to the function within parentheses after the function
name and separated by commas.

Example:
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
[Link](multiply(69));
Output:
69

1.7.10 Calling Functions


After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the
value of parameters enclosed between the parenthesis and a semicolon at the
end. The below syntax shows how to call functions in JavaScript:

Syntax:
functionName( Value1, Value2, ..);
Example:
Below is a sample program that illustrates the working of functions in
JavaScript:
function welcomeMsg(name) {
return ("Hello " + name + " welcome to GeeksforGeeks");
}
// creating a variable
let nameVal = "Admin";
// calling the function
[Link](welcomeMsg(nameVal));
Output:
Hello Admin welcome to GeeksforGeeks
1.7.11 Return Statement
There are some situations when we want to return some values from a
function after performing some operations. In such cases, we can make use of
the return statement in JavaScript. This is an optional statement and most of
the time the last statement in a JavaScript function. Look at our first example
with the function named as calcAddition. This function is calculating two
numbers and then returns the result.

Syntax:
The most basic syntax for using the return statement is:
return value;
The return statement begins with the keyword return separated by the value
which we want to return from it. We can use an expression also instead of
directly returning the value.
Chapter 2: Control Structures and Loops
2.1 Conditional Statements
2.1.1 if Statement
The if statement is used to evaluate a particular condition. If the condition
holds true, the associated code block is executed.
Syntax:
if ( condition ) {
// If the condition is met,
//code will get executed.
}
Example:
This JavaScript code determines if the variable num is even or odd using the
modulo operator %. If `num` is divisible by 2 without a remainder, it logs Given
number is even number. Otherwise, it logs Given number is odd number.
let num = 20;
if (num % 2 === 0) {
[Link]("Given number is even number.");
}
if (num % 2 !== 0) {
[Link]("Given number is odd number.");
};

Output:
Given number is even number.
2.1.2 Using if-else Statement
The if-else statement will perform some action for a specific condition. Here we
are using the else statement in which the else statement is written after the if
statement and it has no condition in their code block.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Example:
This JavaScript code checks if the variable age is greater than or equal to 18. If
true, it logs You are eligible for a driving license. Otherwise, it logs You are not
eligible for a driving license. This indicates eligibility for driving based on age.
let age = 25;
if (age >= 18) {
[Link]("You are eligible of driving licence")
} else {
[Link]("You are not eligible for driving licence")
};
Output:
You are eligible of driving licence
2.1.3. else if Statement
The else if statement in JavaScript allows handling multiple possible conditions
and Outputs, evaluating more than two options based on whether the
conditions are true or false.
Syntax:
if (1st condition) {
// Code for 1st condition
} else if (2nd condition) {
// ode for 2nd condition
} else if (3rd condition) {
// Code for 3rd condition
} else {
// Code that will execute if all
// above conditions are false
}
Example:
This JavaScript code determines whether the constant num is positive,
negative, or zero. If num is greater than 0, it logs Given number is positive. If
num is less than 0, it logs Given number is negative. If neither condition is met
(i.e., num is zero), it logs Given number is zero.
const num = 0;
if (num > 0) {
[Link] ("Given number is positive.");
} else if (num < 0) {
[Link] ("Given number is negative.");
} else {
[Link] ("Given number is zero.");
};
Output:
Given number is zero.
2.1.4. Using Switch Statement (JavaScript Switch Case)
As the number of conditions increases, you can use multiple else-if statements
in JavaScript. but when we dealing with many conditions, the switch statement
may be a more preferred option.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
default:
statementDefault;
};
Example: This JavaScript code assigns a branch of engineering to a student
based on their marks. It uses a switch statement with cases for different mark
ranges. The student’s branch is determined according to their marks and
logged to the console.
const marks = 85;
let Branch;
switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
case marks >= 80:
Branch = "Mechanical engineering";
break;
case marks >= 70:
Branch = "Chemical engineering";
break;
case marks >= 60:
Branch = "Electronics and communication";
break;
case marks >= 50:
Branch = "Civil engineering";
break;
default:
Branch = "Bio technology";
break;
}
[Link](`Student Branch name is : ${Branch}`);
Output:
Student Branch name is : Mechanical engineering
2.1.5. Using Ternary Operator ( ?: )
The conditional operator, also referred to as the ternary operator (?:), is a
shortcut for expressing conditional statements in JavaScript.
Syntax:
condition ? value if true : value if false
Example: This JavaScript code checks if the variable `age` is greater than or
equal to 18. If true, it assigns the string “You are eligible to vote.” to the
variable `result`. Otherwise, it assigns “You are not eligible to vote.” The value
of `result` is then logged to the console.
JavaScript
let age = 21;
const result =
(age >= 18) ? "You are eligible to vote."
: "You are not eligible to vote.";
[Link](result);
Output:
You are eligible to vote.
2.1.6 Nested if…else
Nested if…else statements in JavaScript allow us to create complex conditional
logic by checking multiple conditions in a hierarchical manner. Each if
statement can have an associated else block, and within each if or else block,
you can nest another if…else statement. This nesting can continue to multiple
levels, but it’s important to maintain readability and avoid excessive
complexity.
Syntax:
if (condition1) {
// Code block 1
if (condition2) {
// Code block 2
} else {
// Code block 3
}
} else {
// Code block 4
}
Example: In this example, the outer if statement checks the weather variable. If
it’s sunny, it further checks the temperature variable to determine the type of
day it is (hot, warm, or cool). Depending on the values of weather and
temperature, different messages will be logged to the console.
let weather = "sunny";
let temperature = 25;

if (weather === "sunny") {


if (temperature > 30) {
[Link]("It's a hot day!");
} else if (temperature > 20) {
[Link]("It's a warm day.");
} else {
[Link]("It's a bit cool today.");
}
} else if (weather === "rainy") {
[Link]("Don't forget your umbrella!");
} else {
[Link]("Check the weather forecast!");
};
Output:
It's a warm day.
2.2 Loops
In computer programming, a loop is a sequence of instruction s that is
continually repeated until a certain condition is reached. Typically, a certain
process is done, such as getting an item of data and changing it, and then some
condition is checked such as whether a counter has reached a prescribed
number.
2.2.1 for Loop
A for loop in JavaScript repeatedly executes a block of code as long as a
specified condition is true. It includes initialization, condition checking, and
iteration steps, making it efficient for controlled, repetitive tasks.

Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Example:
// JavaScript program to illustrate for loop
let x;
// for loop begins when x=2
// and runs till x <=4
for (x = 2; x <= 4; x++) {
[Link]("Value of x:" + x);
}
Output:
Value of x:2
Value of x:3
Value of x:4
2.2.2 while Loop
The while loop executes a block of code as long as a specified condition is true.
In JavaScript, this loop evaluates the condition before each iteration and
continues running as long as the condition remains true. The loop terminates
when the condition becomes false, enabling dynamic and repeated operations
based on changing conditions.
Syntax
while (condition) {
Code block to be executed
}
Example:
let count = 1;
while (count <= 5) {
[Link](count);
count++;
}
Output:
1
2
3
4
5
2.2.3 do…while Loop
A do…while loop in JavaScript is a control structure where the code executes
repeatedly based on a given boolean condition. It’s similar to a repeating if
statement. One key difference is that a do…while loop guarantees that the
code block will execute at least once, regardless of whether the condition is
met initially or not.
Syntax:
do {
// Statements
}
while(conditions)
Example:
let test = 1;
do {
[Link](test);
test++;
} while(test<=5)
Output:
1
2
3
4
5
2.2.4 break Statement
JavaScript break statement is used to terminate the execution of the loop or
the switch statement when the condition is true.
 In a switch, code breaks out and the execution of code is stopped.

 In a loop, it breaks out to the loop but the code after the loop is
executed.
Syntax:
break;
Example:
In this example, the loop iterates from 1 to 6 when it is equal to 4 then the
condition becomes true, and code breaks out to the loop.
for (let i = 1; i < 6; i++) {
if (i == 4) break;
[Link](i);
}
Output:
1
2
3
2.2.5 continue Statement
The continue statement in Javascript is used to break the iteration of the loop
and follow with the next iteration. The break in the iteration is possible only
when the specified condition going to occur.
Syntax:
continue;
Example:
let i = 0;
while (i < 11) {
i++;
if (i % 2 == 0) continue;
[Link](i);
}
Output:
1
3
5
7
9
11
Chapter 3: Advanced Functions
3.1 Higher-Order Functions
JavaScript Higher-Order Functions are functions that can accept other functions
as arguments, return functions, or both. They enable abstraction and flexibility
in code, allowing you to create reusable and modular functions for complex
operations, making them essential in functional programming.
Syntax:
function higherOrderFunction(callback) {
// Perform some operations
// Call the callback function
callback();
}
function callbackFunction() {
[Link]("Callback function is executed.");
}
// Passing the callback function to the higher-order function
higherOrderFunction(callbackFunction);
Parameters:
 higherOrderFunction: Takes a callback function, executes it, and performs
operations.
 callback: A function passed as an argument, executed inside
higherOrderFunction.
 callbackFunction(): Logs “Callback function is executed.”
 Invocation: Calls higherOrderFunction(callbackFunction), executing
callbackFunction within higherOrderFunction.
3.1.1 Function as an Argument
This approach involves passing a function (callback) as an argument to another
function. The receiving function can then execute the callback, enabling flexible
and customizable behavior in JavaScript programs.
Example:
In this example, Two functions: greet accepts name and returns a greeting.
greet name combines greeting, message, and name, logging a customized
message. Output: Hi!! JavaScript Welcome To GeeksForGeeks.
function greet(name) {
return `Hi!! ${name} `;}
function greet_name(greeting, message, name) {
[Link](`${greeting(name)} ${message}`);
}
greet_name(greet, 'Welcome To GeeksForGeeks', 'Geeks');
Output:
Hi!! Geeks Welcome To GeeksForGeeks
3.1.2 Functions as Return Values
Higher-order functions can also return new functions. This is often used for
creating specialized functions or closures. For instance, you can create a
function factory that generates functions with specific behavior.
Example
In this example, multiplier is a higher-order function that takes a factor as an
argument and returns a new function that multiplies any number by that
factor. We then use double and triple to create specialized functions.
function multiplier(factor) {
return function (x) {
return x * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
[Link](double(5));
[Link](triple(5));
Output
10
15
3.2 Closures
3.2.1 Overview
Closures in JavaScript are functions that retain access to variables from their
containing scope even after the parent function has finished executing. They
are useful for maintaining private data, creating modular code, and
implementing callback functions with persistent state.
A closure is the combination of a function bundled together (enclosed) with
references to its surrounding state (the lexical environment). When you create
a closure, you gain access to an outer function’s scope from an inner function.
Closures are automatically created every time a function is defined in
JavaScript.
3.2.2 Lexical Scoping
Lexical scoping refers to how a parser resolves variable names when functions
are nested. The location where a variable is declared within the source code
determines where that variable is available. Nested functions have access to
variables declared in their outer scope.
Example
function foo() {
let b = 1;
function inner() {
return b;
}
return inner;
}
let get_func_inner = foo();
[Link](get_func_inner());
[Link](get_func_inner());
[Link](get_func_inner());
Output
1
1
1
We can access the variable b which is defined in the function
foo() through function inner() as the later preserves the scope chain of the
enclosing function at the time of execution of the enclosing function i.e. the
inner function knows the value of b through its scope chain.
This is closure in action that is inner function can have access to the outer
function variables as well as all the global variables.
Closure in JavaScript
Closure is the concept of function + lexical environment in which function it
was created. so every function declared within another function then it has
access to the scope chain of the outer function and the variables created
within the scope of the outer function will not get destroyed.
3.2.3 Creating Closures
Example – 1 : Basic Closure.
function foo(outer_arg) {

function inner(inner_arg) {
return outer_arg + inner_arg;
}
return inner;
}
let get_func_inner = foo(5);
[Link](get_func_inner(4));
[Link](get_func_inner(3));
Output
9
8
In the above example we used a parameter function rather than a default one.
Not even when we are done with the execution of foo(5) we can access
the outer_arg variable from the inner function. And on the execution of the
inner function produce the summation of outer_arg and inner_arg as desired.
Example 2:
// Outer function
function outer() {
let arr = [];
let i;
for (i = 0; i < 4; i++) {
// storing anonymous function
arr[i] = function () { return i; }
}

// returning the array.


return arr;
}
let get_arr = outer();
[Link](get_arr[0]());
[Link](get_arr[1]());
[Link](get_arr[2]());
[Link](get_arr[3]());
Output
4
4
4
4
In the above code, we have created four closures that point to the variable i
which is the local variable to the function outer. Closure doesn’t remember the
value of the variable it only points to the variable or stores the reference of the
variable and hence, returns the current value. In the above code when we try
to update the value it gets reflected all because the closure stores the
reference.
Example 3:
// Outer function
function outer() {
function create_Closure(val) {
return function () {
return val;
}
}
let arr = [];
let i;
for (i = 0; i < 4; i++) {
arr[i] = create_Closure(i);
}
return arr;
}
let get_arr = outer();
[Link](get_arr[0]());
[Link](get_arr[1]());
[Link](get_arr[2]());
[Link](get_arr[3]());
Output
0
1
2
3
In the above code we are updating the argument of the function
create_Closure with every call. Hence, we get different values of i at different
indexes.
3.2.4 Common Use Cases
 Maintaining State: Closures help maintain state between events in event-
driven JavaScript.
 Private Variables: You can create private variables by enclosing them within
a closure.
 Callbacks and Asynchronous Code: Closures are essential for handling
callbacks and asynchronous operations.
3.3 Callbacks and Promises
In JavaScript, managing asynchronous operations is a key aspect of modern
web development. Two popular approaches for handling these operations are
Promises and Callbacks.
3.3.1 Promises
To manage asynchronous actions in JavaScript, promises are used. It is an
assurance that something will be done. The promise is used to keep track of
whether the asynchronous event has been executed or not and determines
what happens after the event has occurred.
A Promise has four states:
 fulfilled: Action related to the promise succeeded

 rejected: Action related to the promise failed

 pending: Promise is still pending i.e. not fulfilled or rejected yet

 settled: Promise has fulfilled or rejected

Syntax:
Let promise = new Promise (function (resolve, reject) {
// do something
});
A promise can be created using Promise constructor.
Parameters:
 Promise constructor takes only one argument which is a callback function
(and that callback function is also referred as an anonymous function too).
 Callback function takes two arguments, resolve and reject

 Perform operations inside the callback function and if everything went well
then call resolve.
 If desired operations do not go well then call reject.

Example:
In this example, a Promise is created to compare two strings, geeksforgeeks
and geeksforgeeks. If the strings match, the promise resolves, logging a success
message. Otherwise, it rejects, logging an error message. The then method
handles success, and the catch method handles errors.
let promise = new Promise(function (resolve, reject) {
const x = "geeksforgeeks";
const y = "geeksforgeeks"
if (x === y) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
[Link]('Success, You are a GEEK');
}).
catch(function () {
[Link]('Some error has occurred');
});

Output
Success, You are a GEEK
Benefits of Promises:
 Improves Code Readability

 Better handling of asynchronous operations

 Better flow of control definition in asynchronous logic

 Better Error Handling

3.3.2 Callbacks
Callbacks are a great approach to dealing with something once another task
has been finished. Here, something refers to the execution of a function.
Callbacks can be utilized if we wish to run a function immediately following the
return of another function.
The type of JavaScript function is objects. They may therefore be supplied as an
argument to any other function when calling them, just like any other objects
(Strings, Arrays, etc.).
Example:
In this example, the add function takes two numbers, adds them, logs the
result, and executes a callback function (disp). When calling add(5, 6, disp), it
outputs the sum and a message from the callback.
// The add() function is called with arguments a, b and callback, callback
// will be executed just after ending of add() function
function add(a, b, callback) {
[Link](`The sum of ${a}
and ${b} is ${a + b}`);
callback();
}
// The disp() function is called just after the ending of add() function
function disp() {
[Link](`This must be printed
after addition`);
}
// Calling add() function
add(5, 6, disp)

Output:
The sum of 5 and 6 is 11
This must be printed after addition
Explanation:
Here are the two functions – add(a, b, callback) and disp(). Here add() is called
with the disp() function i.e. passed in as the third argument to the add function
along with two numbers.
As a result, the add () is invoked with 1, 2, and the disp () which is the callback.
The add() prints the addition of the two numbers and as soon as that is done,
the callback function is fired! Consequently, we see whatever is inside the
disp() as the output below the additional output.
The benefit of Callback:
 You can run another function call after waiting for the outcome of a prior
function call.
 You can call the parent function from the child function and can also pass
data from child to parent.
Chapter 4: Asynchronous JavaScript
4.1 Async/Await
Async and Await in JavaScript is used to simplify handling asynchronous
operations using promises. By enabling asynchronous code to appear
synchronous, they enhance code readability and make it easier to manage
complex asynchronous flows.
4.1.1 Async Function
The async function allows us to write promise-based code as if it were
synchronous. This ensures that the execution thread is not blocked.
 Promise Handling: Async functions always return a promise. If a value is
returned that is not a promise, JavaScript automatically wraps it in a
resolved promise.
Async Syntax:
async function myFunction() {
return "Hello";
}
Example:
const getData = async () => {
let data = "Hello World";
return data;
}
getData().then(data => [Link](data));
Output:
Hello World
4.1.2 Await Keyword
The await keyword is used to wait for a promise to resolve. It can only be used
within an async block.
 Execution Pause: Await makes the code wait until the promise returns a
result, allowing for cleaner and more manageable asynchronous code.
Syntax:
let value = await promise;
Example:
const getData = async () => {
let y = await "Hello World";
[Link](y);
}
[Link](1);
getData();
[Link](2);
Output
1
2
Hello World
The async keyword transforms a regular JavaScript function into an
asynchronous function, causing it to return a Promise.
The await keyword is used inside an async function to pause its execution and
wait for a Promise to resolve before continuing.
4.1.3 Async/Await Example
Here, we will be implementing several promises in a method, and then that
method we will use for displaying our result. You can check the JS async/await
syntax in the example.
function asynchronous_operational_method() {
let first_promise =
new Promise((resolve, reject) => resolve("Hello"));
let second_promise =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(" GeeksforGeeks..");
}, 1000);
});
let combined_promise =
[Link]([first_promise, second_promise]);
return combined_promise;
}
async function display() {
let data = await asynchronous_operational_method();
[Link](data);
}
display();
Output:
[ 'Hello', ' GeeksforGeeks..' ]
Explanation:
 Promise Creation: Two promises are created: one resolve immediately with
“Hello”, and the other resolves after 1 second with ” GeeksforGeeks..”.
 Combining Promises: The [Link]() method combines both promises
into a single promise, combined_promise.
 Asynchronous Function: The display() function is declared as async,
indicating it contains asynchronous operations.
 Awaiting Promise Resolution: The await keyword pauses execution until
combined_promise is resolved.
 Logging Result: The resolved array from combined_promise is logged to the
console.
Note
To resolve and reject are predefined arguments by JavaScript.
 resolve function is used when an asynchronous task is completed and
returns the result.
 reject function is used when an asynchronous task fails and returns reasons
for failure.
4.1.4 Error Handling in Async/Await
JavaScript provides predefined arguments for handling promises: resolve and
reject.
 resolve: Used when an asynchronous task is completed successfully.

 reject: Used when an asynchronous task fails, providing the reason for
failure.
Example:
async function fetchData() {
try {
let response = await fetch('[Link]
let data = await [Link]();
[Link](data);
} catch (error) {
[Link]('Error fetching data:', error); }
}
4.1.5 Advantages of Async and Await
1. Improved Readability: Async and Await allow asynchronous code to be
written in a synchronous style, making it easier to read and understand.
2. Error Handling: Using try/catch blocks with async/await simplifies error
handling.
3. Avoids Callback Hell: Async and Await prevent nested callbacks and
complex promise chains, making the code more linear and readable.
4. Better Debugging: Debugging async/await code is more intuitive since it
behaves similarly to synchronous code.
4.2 Fetch API
4.2.1 Overview
The fetch() method in JavaScript is a modern and powerful way to retrieve
resources from a server. It returns a Promise that resolves to a Response
object, encapsulating the server’s response to your request.
fetch() seamlessly integrates advanced HTTP functionalities such as Cross-
Origin Resource Sharing (CORS) and other extensions, enriching the web
development experience with enhanced security and interoperability.
Note: Fetch API comes with the fetch() method, which is used to fetch data
from different sources.
Syntax:
fetch('url') // api for the get request
.then(response => [Link]())
.then(data => [Link](data));
Parameters:
 URL: The URL to which the request is to be made.
 Options: It is an array of properties. It is an optional parameter. Options
available are:
o Method: Specifies HTTP method for the request. (can be GET, POST, PUT
or DELETE)
o Headers

o Body: Data to be sent with the request.

o Mode: Specifies request mode (eg. cors, nocors, same-origin, etc)

o Credentials: Specifies whether to send user credentials (cookies,


authentication headers, etc.) with the request
4.2.2 JavaScript fetch() Method Examples
1. Get Request Using Fetch
This example shows how to make Get request in fetch method.
Note: Without options, Fetch will always act as a get request.
// API for get requests
let fetchRes = fetch(
"[Link]
// FetchRes is the promise to resolve
// it by [Link]() method
[Link](res =>
[Link]()).then(d => {
[Link](d)
})
Output:

Explanation:
1. The JS fetch() function is used to send a GET request to the URL
[Link] This function returns a
Promise that resolves to a Response object representing the response to the
request.
2. The then() method is chained to the fetch() call to handle the response
asynchronously. Inside the callback function passed to then(), the [Link]()
method is called to parse the response body as JSON. This method also
returns a Promise that resolves to the parsed JSON data.
3. Another then() method is chained to handle the parsed JSON data. Inside its
callback function, the parsed JSON data d is logged to the console using
[Link]()
2. Using fetch to Post JSON Data
In this example, we have uploaded JSON data using the fetch() API in
JavaScript, you can set the request body to a JSON stringified version of your
data and set the appropriate headers to indicate that you’re sending JSON.
Post requests can be made using fetch by giving the options given below:
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: [Link](data)
}
After checking the Syntax of the post request, look at the example below which
demonstrates using post request in fetch method.
// Your JSON data
const jsonData = { key1: 'value1', key2: 'value2' };

// Set up options for the fetch request


const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json' // Set content type to JSON
},
body: [Link](jsonData) // Convert JSON data to a string and set it as
the request body
};

// Make the fetch request with the provided options


fetch('[Link] options)
.then(response => {
// Check if the request was successful
if (![Link]) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON
return [Link]();
})
.then(data => {
// Handle the JSON data
[Link](data);
})
.catch(error => {
// Handle any errors that occurred during the fetch
[Link]('Fetch error:', error);
});
Explanation:
 We define your JSON data.
 We set up options for the fetch request, including the method set to POST,
the Content-Type header set to application/json, and the body set to the
JSON stringified version of your data.
 We make the fetch request with the provided options using the fetch()
function.
 The rest of the code remains the same as before, handling the response and
any errors that occur during the fetch.
3. Aborting a Fetch Request
You can use the AbortController and AbortSignal Interface to abort a fetch
request in JavaScript.
// Create a new AbortController instance
const controller = new AbortController();
const signal = [Link];

// Make the fetch request with the signal


const fetchPromise = fetch('[Link] { signal });

// Timeout after 5 seconds


const timeoutId = setTimeout(() => {
[Link](); // Abort the fetch request
[Link]('Fetch request timed out');
}, 5000);

// Handle the fetch request


fetchPromise
.then(response => {
// Check if the request was successful
if (![Link]) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON
return [Link]();
})
.then(data => {
// Handle the JSON data
[Link](data);
})
.catch(error => {
// Handle any errors that occurred during the fetch
[Link]('Fetch error:', error);
})
.finally(() => {
clearTimeout(timeoutId); // Clear the timeout
});
Explanation:
 We create a new AbortController instance and obtain its signal.

 We make the fetch request using fetch() with the provided options.

 We set a timeout of 5 seconds using setTimeout() to abort the fetch request


if it takes too long.
 Inside the timeout callback, we call [Link]() to abort the fetch
request.
 We handle the fetch request as usual, including parsing the response and
handling any errors.
 Finally, in the finally() block, we clear the timeout using clearTimeout() to
prevent the timeout from triggering if the fetch request completes before
the timeout expires.
4. Sending a request Including Credentials
To send a request including credentials, such as cookies, in a fetch request, you
can set the credentials property to include.
fetch("[Link] {
credentials: "include",
});
If you only want to send credentials if the request URL is on the same origin as
the calling script, add credentials: ‘same-origin’.
// The calling script is on the origin '[Link]
fetch("[Link] {
credentials: "same-origin",
});
4.2.3 JavaScript fetch() Method Use Cases
Here are some of the use cases of the fetch method. These are common issues
that beginner developers face when working with fetch.
 Retrieving Data with GET Requests: Ideal for fetching data from a server.

 Sending Data with POST Requests: Easily send data to a server by


configuring the request method and body.
 Difference Between fetch() and Axios: fetch() is built into modern browsers
and doesn’t require installation, unlike Axios, which is a third-party package
offering additional features.

Chapter 5: Working with Data


5.1 JSON
5.2 Local Storage and IndexedDB
Chapter 6: DOM Manipulation
6.1 Selecting and Modifying DOM Elements
6.2 Event Handling
Chapter 7: Object-Oriented JavaScript
7.1 Prototypes and Inheritance
7.2 ES6 Classes
Chapter 8: JavaScript ES6+ Features
8.1 Destructuring and Spread Operator
8.2 Template Literals and Modules
Chapter 9: Debugging and Testing
9.1 Debugging Techniques
9.2 Testing JavaScript

You might also like