0% found this document useful (0 votes)
1 views73 pages

JavaScript M8 Notes

Uploaded by

eng21cs0213
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)
1 views73 pages

JavaScript M8 Notes

Uploaded by

eng21cs0213
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 M8 Batch

JavaScript
JavaScript is a high-level scripting language used to create
interactive and dynamic web pages.

It runs on both the client side (Browser) meaning we can directly


execute the js file on the browser, and server side meaning JS can run
on the server side without a browser using a runtime envirenment
called Nade JS.
Note: Runtime Environment is a platform where your program will be
executed.

It is the only programming language that browsers can understand.

Characteristics of JS

« Scripting language : It is used to automate tasks as JavaScript is


already given to the browser whenever you make the request for any
website. Now for every action of the user javascript will be executed in
the browser side(client side) and it will affecr the UI accordingly.

= Dynamically typed language : JavaScript allows variables to hold


any data type.

leta =10 // initiallya number


a = "JavaSeript™ // now a string

= High level language : which is easily understandable by us human


beings

* Weakly / Loosely typed language : Ir doesn't perform strict type


checking.
= Akshay Thakur />
< JSpiders BTM Layout />
consoleldog( "5” +5) // Outputs “55" ( string concatenation )
consolelog( “5"-2) // Outputs 3 ( string converted to number)

Interpreted Language / Synchronous / Single Threaded


Interpreted — it can be executed directly to machine code , prior
compilation is not needed ( Mo separate compiled file is created).

Synchroneous
— It will be executing all the tasks in the order they are
written .
Single Threaded — It con execute one task af a time , it cannot
execute multiple tasks simultaneously.

Object Based Language : Everything in JavaScript is considered as


an object like arrays, function etc,

Object Oriented Programming Language : JavaScript was


originally object-based, but now it supports Object eriented
programming through ESé+ features like classes and inheritence.
Light-weight Language : It can be directly executed in the browser
easily.

= Akshay Thakur />


< JSpiders BTM Layout /=
History Of JavaScript

ommuni srporations

on Eich (1995)

Mocha

aScript

ECMASCcript

= 1In 1994, a company called Netscape Communicatiens Corporation

created a web browser named Metscape Navigator.


= Initially, this browser only supported static web pages (where content

remained the same for all users).

= To enable dynamic web pages, Netscape hired Brendan Eich in 1995.

= In just 10 days, Eich developed a new scripting language called

Mocha.
» Mocha was later renamed LiveScript, and then finolly JavaScript .
= 1In 1997, JovaScript was standardized os ECMAScript (ES) by ECMA

Internatienal.

Important JavaScript Versions:

= ES55 (2009) — Introduced strict mode and JSON support.

= ES6 (2015) — Added let, const, arrow functions, classes, and many

ofther modern features.

iy / >
« JSpiders BTM Layout />
Java v/s JavaScript

Java JavaScript
Programming language Programming and Scripting
language

Strictly typed Weekly / Loosely typed

Statically typed Dynamically typed

Runs on Java Virtual Machine Runs on all the browsers

Both compide led and interpreted


language Only interpreted longuage

How JavaScript Engine Works


A JovaScript engine is a program that executes JavaScript code. It converts
JavaScript code into machine code thar a computer can understand.

Basically JovaScript code is executed in three Phases —

A. Parsing
B. Compilation
C. Execution

A. Parsing

1. Parser:

= Breoks row JavaScript code into tokens (smallest meaningful units like
keywords, operators, efc.).
= Converts fokens into an Abstract Syntax Tree (AST) {a free structure
representing the code’s syntax),
» Throws errors if there are syntax mistakes.

B. Compilation

< Akshay Thakur />


< J5piders BTM Layout />
2 Interpreter:

= Takes the AST and converts it into bytecode (a low-level, platform-ind


veve v v v bvg bhnQppOp0o-[/ependent cade).
= Executes the bytecode line by line for fast startup.
= Bytecode execution is quick but not as fast os optimized machine
code.

3. Compiler (JIT - Just-In-Time Compiler):


= Works alongside the interprefer to eptimize performance.
s llses the profiler to find hot code {code that runs repeatedhy).
s Compiles the hot code into optimized machine code (native code) for
faster execution
= Reploces the unoptimized bytecode with the optimized machine
code seamlessly.

Simplified Flow:
1. jscode
— pfx x xc ex cx cxxx cv ¢ vev ccv cfcf vicv fv f v vv bgfv
bgf vgbfarser — AST — Interpreter — Bytecode (executed directly).
2. Bytecode — Profiling — JIT Compiler — Optimized Machine Code.
3. Unoptimized Bytecode — Replaced by Optimized Machine Code.

< Akshay Thakur />


< JSpiders BTM Layout />
.y

Machine
Code

C. Execution

= JavaScript code is executed using two main memory areas:

1. Call Stack— Where function calls and execution happen.


2. Heap Memory — Where objects are stored.
= The execufion happens inside the Call Stack, and objects are stored in the

Heap.

< Akshoy Thakur />


< JSpiders BTM Layout />
Object in

- : memary
Execution

N — i
context -

e
_ ]

- ™
CALL STACK HEAP

How_is it u| code Where objects


compiled? 15 execuled are stored

JS Engine of Different Browsers


= Ewvery Browser is having a JavaScript Engine
= But the most Popular JS Engine is V8 engine of Google’s chrome
browser , which is also used in Nodejs

Ways to Execute JavaScript


JavaScript code can be written in two ways:

1. Internal JavaScript
2. External JavaScript
< Akshay Thakur />
< JSpiders BTM Layout />
Internal JavaScript
JavaScript code is written within the same HTML file inside the <script> tag.

Example:
<IDOCTYPE html>
<html>
<head>
<titlesInternal JovaScript«/title»
</head»
<body>
<scripts
var sname = "Akshay”;
consolelog(sname);
</script>
</body:=
</html>

External JavaScript
JavaScript code is written in a separate file, and the HTML file links to it
using the <script= tag with the src aftribute.

Example:

[Link]

<\DOCTYPE htmi>
<htmilz
<head>
<titlesExternal JovaScripte ftitle>
</head>
<body>
<script sre="[Link]"></script>
</body>
</htmis

= Akshay Thakur />


< JSpiders BTM Layout />
[Link]

var sname = "Akshay";


consolelog(sname);

defer
Defer is used to stop the execution of the javascript until complete html is loaded .
We must use defer if we are attaching the js file in the head section.

Example

seriptjs
oonsolelog{"Hey i am script™);

[Link]
consolelog{"Hey i am second");

[Link] — without defer keyword

<html lang="en">
<head>
<meta charset="UTF-87 />
<meta name="viewpart” cantent="width=device-width, initial-scale=1.0" />
<title>Documents/titles
<script sre="./scriptjs"s< /scripts

«/head>

<body>
<script sre="./second
js" =< /script>
</body>
</html=

Qutput
Hey i am script
Hey i am second

Here both the file are getting executed in the same order as they have been written.

[Link] — with defer keyword

< Akshay Thakur />


< JSpiders BTM Layout />
<html lang="en">
<head>
<mata charset="UTF-8" />
«meta name="viewport” content="width=device-width, initial-scale=1.0" />
«<title>Documents/titles
«script sro="./scriptjs” defers«/script>
</head:
<body>
<script sro="/[Link]"
< fscripts
«/body>
</html=

Qutput
Hey i am second
Hey i am script

Here it has stopped the execution of scriptjs until the body is completely loaded.
And inside the body secondjs s there so that is loaded first

Tokens
The smallest unit of a programming language.

Keywords

Predefined words that have a special meaning(purpose) in JavaScript. They


are always in lowercase.

Identifiers

« Name given to variables, classes, functions, or methods.


Cannot start with a number but can contain numbers within.
Cannot be a keyword.
« Can only contain special characters 5 and __
« Should not contain spaces.

Literals

A literal is a fixed value written in a program's source code. Literals can


represent different data types, such as:

< Akshay Thakur />


= JSpiders BTM Layout />
« Number literals: 18, 288, -58
o String literals: "Hello"™, 'World'
+ Boolean literals: true false

Variable Declarations in JavaScript


JavaScript allows declaring variables in thres ways:

In JavaScript, var, let, and const are keywords used to declare


variables.

L wvar
2 let
5. Const

Keyword var let const

Declaration v o x

Initialization v v *

Re-declaration v x *

Re-initialization v < x

Declaration +
Initialization v 4 <

< Akshay Thakur />


< JSpiders BTM Layout />
var a; // declaration
a = 18; // initialization
var al = 2@; // dec+init
var a; // redeclaration
var a = 48; //red+reinitialization

let b; fideclaration
b =40; // init
let bl = 30; /f dec+init;
let b1; flredeclaration is not possible

const ¢; // dec not possible


const ¢l = 38; //dec+init;
const ¢l ; // redec is not possible
const ¢l = 38; // redec+reinit not possible

JS Code inside Call Stack


Js Code is executed in two phases in call stack |, for the first time all the
declaration happens
For the second time again from the first line the execution will happen

Example 1
war a; f/dec
a = 20; /finit
a = 50; /f reinit
var al = 40; // dec+init
var o /f redec
wvar al = 30 // redec+reinit
conseleloglal);

< Akshay Thakur />


< JSpiders BTM Layout />
Example
2

let by // declaration
b =30; // initialization
b = 40; //re-initialization
let bl = 50; // declaration+initialization
/#let bl; // re declaration is not possible

p—= Lnainfinad

< Akshay Thakur />


< JSpiders
BTM Layout />
a=20;
[Link](a); //20
vara;
J/b =40

letb;
[Link]);
b=40;
[Link]);
const ¢ = 50;
[Link](c);

a=20
[Link]{a):
var a;
comment code will stop o errar = 40, [ not Wt‘?am
€ in this line enly
thie line //before initialization-->error

BB =———=} = undefined
consolelag(b);
b=40,
consolelog(b);
const ¢ = 50;
conseoleleg(c)

< Akshay Thakur />


/>
BTM Layout
< JSpiders
20
undufined

Note —
If a variable is already initialized with some value, then only you can
access it before the line in which it is declared.

In this case, the first phase is the memory allocation phase, and during
memory allocation, the variable declared with var will be initialized
with a default value called undefined (undefined is a data type in
JavaScript). That's why we are able to access it before the line in which
it has been declared.

But in the case of let and const, there is no value initialized at the time
of declaration, so we cannot access them before the line in which they
are declared

Hoisting

Hoisting is the process in Javascript where functions and variables can be


used before the line in which they are declared.

< Akshay Thakur />


< JSpiders BTM Layout />
OR

Hoisting is the process of moving variable and function declarations to the


top of their scope before execution.

= Only var can be accessed before declaration

/7! accessing the a in line mmber 1 but it is declared in


1ine 2
[Link](a): // undefined
var
a = 10;

let and const are hoisted but remain in the Temporal Dead Zone unil
initialized.

Temporal Dead Zone


variables declared with let and const are hoisted to the top of a block
in JavaScript. However, they are not initialized, so they cannot be used
until they are declared. This is known as the temporal dead zone (TDZ).

[Link]{al; // Uncaught Reference Error Can't access a before

let a = 10;

Data Types
Data types specify the type of values stored in variables)\

< Akshay Thakur />


< JSpiders BTM Layout />
[Link] 1.0bject
2.5tring
[Link]
4. Null
[Link]
[Link]
7.5ymbol

Operators in JavaScript
Operators are special symbaols that perform operations on values.

Arithmetic Operators:

=+ [Addition)
s - (Subtraction)
s " [Multiplication)
=/ {Division)
s % (Modulus)
= " (Exponentiation)

Assignment Operators:
s = (Assign)
+= (Add and assign)
-= (Subtract and assigm)
"= (Multiply and assign)
/= (Divide and assign)
%= {Modulus and assign)

Relational (Comparison) Operators:


® < (Less than)
s = (Greater than)
s <= (Less than or equal ta)

< Akshay Thakur />


< JSpiders BTM Layout />
»= (Greater than or equal fo)
s == (Equality check, value anly)
s === (Strict equality check, value and data type both)
s = (Not equal ta)

Logical Operators:
» GE(AND)
* [ (OR)
s [(NOT)

Ternary Operator:

s (condition) ? true_value : false_value;


* Alternative fo if-else.

Conditional Statements
Conditional statements execute specific code blocks based on conditions.

1. if Statement

s Executes code only if the condition is frue.

Syntax:
i (eondition) {
/{ Code to execute
+

2. if-else Statement

s Executes one block if true, another if false.

Syntax:
if (condition) {
[/ 1f block code
}else {
/{ Else block code
}

< Akshay Thakur />


< J5piders BTM Layout />
3. else if Statement
s Used for multiple conditions.

Syntax:
if (conditionl) {
/f Code block 1
} else if (conditionZ) {
/f Code block 2
}else {
/¢ Default block
1

4. Nested if

« i statements inside another if.

Syntax:
if {conditionl) {
if (condition2) {
/i Nested if code
}
1

5. switch Statement

= Matches values against cases,

Syntax:
switch (expression) {
case valuel:
/f Code for casel
break;
case value2:
// Code for case2
break;
default:
/f Default case

Truthy and Falsy values


In JavaScript, a value is considered truthy if it coerces to true when evaluated in a Boolean
context. All values are truthy unless they are defined as falsy.
< Akshay Thakur />
< JSpiders BTM Layout />
Sa this type coercion happens in two scendarios

LLogical operators

2In a logical context like if else statement

Falsy values in JavaScript are:

false
0 {and -0)
On (BigInt zero)
™ {empty string)
null
undefined
NaM

All other values are truthy, including:


true
Any non-zero number
Any non-empty string
[1 empty array)
{} (empty object)
function() {} (empty function)

let money =0,

if {money) {

consolelog("don't spend it all"y;

}else{
consolelog("you should get a job™);

Type Conversion

< Akshay Thakur />


< JSpiders BTM Layout />
Type conversion (or typecasting) means transfer of data from one data type
to another

Implicit Type Conversion{Coercion) - Implicit conversion happens when the


compiler or runtime automatically converts data types.
Eg-5-'F = 2
5+3 =53
If we use numeric string with any other operator other than +, the operand
will be converted to numeric type

Explicit Type Conversion - Conversion from one data type to another


explicitly it might lead to dafo loss
Converting to Number - Number() - Returns a number, converted from its
argument
parseFloat() - Parses a string and returns a floating point number
parselnt() - Parses a string and returns an infeger
Converting to String - String() - Returns a string, converted from its
argument
Converting to Boolean - Boolean() - Returns a boalean, converted from its
argumant

== - Allows coercion
=== - Does not allow coercion
0 == ‘0" = True
0==" = True
0 === " - False
false == - True

Looping Statement
Looping statements are used to execute a block of code multiple fimes until a
condition is met.

1. While Loop

» Executes as long as the condition is frue.


+ Requires initialization before the loop and updation inside the loop.

Syntax:

letii =1;
while (i <= 5] 1

< Akshay Thakur />


« JSpiders BTM Layout />
cons=[Link]);
i+t:

2. For Loop
s Used when the number of iterations is known.
« Combines initlalization, condition, and updation in a single line.

Syntax:
for (let i = 1: 4 <= 5; i+#) {
corsole. log (i) ;

Taiking User Input

let 5 = prompt {"Enter a string:"};

let n = Humber (prompt ("Enter a number:"}];

for (let i = 0; 1 < n; 1+¥)} |


console_logis);

3. do-while Loop

The do-while loop executes the block of code at least once, even if the condition is
false. 1t is known as an exit-controlled loop becouse the condition is checked after
executing the loop body.

s Executes at least once before checking the condition.


= Repeats as long as the condition is frue.

Syntax:

leti=1; // Initialization

do{

consalelog(); // Code to axecute

< Akshay Thalkur />


< JSpiders BTM Layout />
i+ // Updation

} while (i <= 5); // Condition

Function

A function is a reusable block of code that performs a specific task when invoked.
Functions improve code readability, maintainability, and efficiency.

Parameters and Arguments


s Parameters: Variables listed in the function definition.
= Arguments: Actual values passed to the function.

Example:

function add{a, b) {
return a + by
}
console logladd(s, 10)); // Output:15

Default Parameters

1f a parameter is missing, it defoults to undefined, but you can set a defoult value,

function sum(x, y = 103{


return X + v,
!
consolelog(sum(s)); // Output; 15

Return Statement

s Stops function execution ond returns a value.


s If no volue is returned, the function returns undefined,

Example:

= Akshay Thakur />


< JSpiders BTM Layout />
function multiply(a, b) {
returna * b
¥
console log{multiply(e, 103); // Output: 60

Function Invocation

« A function runs only when it is invoked.


# You can invoke the function as many fimes as you want

yFunetion(10, 2)

Example:

function myFunction{a, b){


returna * b
¥
consolelogimyFunction(10, 2)); // Output: 20

Types Of Functions
1. Named Function
2. Anonymous Function
3. First Class Function

5. Immediate invoke Function Expression (IIFE)


&, Arrow Function

8. Callback Function
9. Nested Function
[Link] Function

1. Named Function:
A function declared with an identifier name
Maomed Functions can be hoisted (accessed before declaration)
f/ 7 Syntax:
function fMame(params) {

= Akshay Thakur />


< JSpiders BTM Layout />
// block of code

}
fNaome(args);

// 7 Exomple:
function sumia, b) {
return a + b;

}
consolelog(sum(10, 200); /7 30

2. Anonymous Function:
A function declared without an identifier.
It needs to be stored in a variable for execution.

/7 Syntax:
var variableMame = function (params) {
// Code
E
variableMame(args);

// 7 Example:
var add = function (a, b) {
return a + b;

k
consolelog(add(10, 20)); // 30

3. First Class Function:


A function that is treated as a value and assigned to a variable.
It can be a named, anonymous, or arrow function.
First-class functions cannot be accessed directly without variable names.

< Akshay Thakur />


< JSpiders BTM Layout />
‘var greet = function () {
[Link]("Hello, World!™);

L
greet(};

4. Function Expression:
An expression of storing any function into a variable (already covered in
anonymous functions).

5. Immediately Invoked Function Expression (IIFE):


This function is executed immediately after its definition.
The first parenthesis indicates the function,
the second indicates invocation, and the semicolon indicates the end.

// ? Syntax:
{function () {
// Code
o

J/ 7 Example 1:
(function (a, b) {
[Link](a + b);
110, 20; /¥ 50

J/ 2 Example 2 (with Arrow Function):


((a) => [Link]{a ** 2))(10); // 100

&. Arrow Function:


An advanced and concise syntax for writing functions.
It reduces code length and offers a simplified syntax.
< Akshay Thakur />
< J5piders BTM Layout />
//
7 Syntax:
vars={a)=>a* 2,

consolelog(s(107); // 100

If there is only one parameter, parentheses are optional:


var square =a=>a* 2;
[Link](square(10}); // 100

// Implicit return
In arrow functions, an implicit return allows you to return a value without
using the return keyword or curly braces {}. This is useful when the
function has only a single expression.

7. Higher Order Function:


A function that accepts another function as an argument or returns a
function is called as a higher order function

function higherOrder(fn) {
[Link]("Before executing callback™);

fn();
consolelog("After executing callback™);
}

higherOrder(() => [Link]("Callback function executed"));

B. Callback Function:
A function passed as an argument to another function is called as
callback function

function colculate(n, b, operation) {


= Akshay Thakur />
< JSpiders BTM Layout />
return operation(a, b);

function sum(a, b) {
return o + b;
}

function sub(a, b) {
return a - b;
}

function mui(a, b) {
return a * b;
}

[Link](calculate(10, 20, sum}); // 30


consolelog(calculate(10, 20, sub)); // -10
[Link](calculate(10, 20, mul)y; // 200
// ? Here, 'calculate’ is the Higher Order Function
J/ and 'sumy, 'sub’, 'mul’ are Collback Functions.

1. Closure:
When a nested function requires the variable of its parent function,
JavaScript creates closures that hold only the required variables.
Closures allow a function to access variables from its outer scope even
after the outer function has finished executing.

function parentFunction() {
let parentVar = "I'm a parent variable";

function childFunction() {
consolelog{parentVar); // Accessing parent's variable
]~
< Akshay Thakur />
< J5piders BTM Layout />
return childFunction;

const child = parentFunction();


child{); /7 "I'm a parent variable”

Ex 2
function outerFunction(x) {
function innerFunction(y) {
return x + y;

3
return innerFunction;
b

‘const add5 = outerFunction(5);


[Link](add5(2)); // Output: 7

//! Creating counter with closure

function counter() {
let count = 0;
return function getCount() {
[Link](++count);

}
let rescounter = counter()
rescounter() // 1
rescounter() //2

< Akshay Thakur />


< JSpiders BTM Layout />
Strings
A string is o collection of characters enclosed in ", ™ or
£V Exs
var sl = "JavaScript’
var s2 = "JavaScript”;
var s3 = " JovaScript”;

String Interpolation:
It is the process of [Link] ng variables er solving an expression inside
a
string using backticks (* ")
I PEX
var Ename = "Chetna”;
var sal = 100;
consolelog(”Dear ${Ename}, your salary is ${sal}
"}

// 7 NOTE:
// In string interpolation, we must use only backticks (" ")

// ! Length Property:
/7 It helps to find the length of a string.
e
var s = "JavaScript™;
consolelog(s); // "JavaScript”’
consolelog([Link]); // 10

String Methods:

toLowerCaose(), toUpperCase(), toString(), trimStart(),


trimEnd(), trim(), replace(), reploceAll(), substr(),
substring(), slice(), split(), concat(), indexOf(),
lastIndexOf(), includes(), charAt(), charCodeAt(),
[Link]()

i
< Akshoy Thakur />
< JSpiders BTM Layout />
/7 ! toLowerCase():
// Converts all characters to lowercase.

/f ? Syntax:
[Link]();

ff?Ex:
var s = "JavaScript”;
[Link]([Link](}); // "jovascript”

// ! foUpperCase():
/# Converts all characters
to uppercase.

/f ? Syntax:
[Link]();

ffPEX
var s = "JavaScript”;
[Link]([Link]()); // "JAVASCRIPT"

/7 ! toString(x
// Converts a variable’s data type into a string format.
// 2 Syntax:
[Link]();
S PER
wvar n = 10;
consolelog(n); // 10
consolelog(typeof ny; // "number”
vars= [Link]();
consolelog(s); // "10"
consoleog(typeof s); // "string”

// ¥ trimStart(), trimEnd(), trim():


// Removes unwanted spaces from the start, end, or both.
/1t Syntax:
[Link](); // Removes leading spaces
« Akshay Thakur />
< JSpiders BTM Layout />
[Link](); // Removes trailing spaces
[Link](); // Removes spaces from both ends

/T EX:
\f:i_rs =" JavaScript ";
[Link](s), // " JavaScript "
[Link]); // 14
[Link]([Link]()); // "JavaScript "
[Link]([Link]().length); // 12
consalelog([Link]()); // " JavaScript”
[Link](}.length); // 12
consolelog([Link]()); // "JavaScript”
[Link]([Link]([Link]); // 10

/f ! replace():
// Replaces the first occurrence of
a substring.
/f 7 Syntax:
[Link]("existingCharacter”, "newCharacter”);
/2 Ex:
vars = "Hii Hii Hii";
[Link]([Link]("Hii", "Bye™)); // "Bye Hii Hii"

/1 ! replaceAll():
/f Replaces all occurrences of a substring.
// 7 Syntax:
[Link]("existingCharacter”, "newCharacter™);
VB
var s = "Hii Hii Hii";
[Link]([Link]{"Hii", "Bye")); // "Bye Bye Bye"

// 1 substr():
J// Extracts a portion of the string (deprecated in modern JavaScript).
/f T Syntax:
< Akshay Thakur />
< JSpiders BTM Layout />
[Link]{startIndex, length);
M TER
vars = "I Love JavaScript”;
t:.c-rnsoie,lug(susubsir{:!, 4% /f "Love™

/7 ! substring():
/{ Extracts a portion of the string.
/7 Syntax:
variableName substring(startIndex, endIndex);
JTEX
vars ="I Love JavaScript™;
cfinsoie,lcg([Link](l, &3 /7 "Love"

/7 ! slice():
/¢ Extracts a portion of the string (similor to substring).
J/ 7 Syntax:
variableMame slice(startIndex, endIndex);
/T Ex
vars = "I Love JavaScript”;
console log([Link](2, 6); // "Love"

// 7 NOTE: The ending index is not included in substring() and slice().

71 split:
// Splits a string into an array based on a delimiter.
[/ 7 Syntax:

[Link](parameter);
JFTEX
vars = "I Love JavaScript”;
consoleJog([Link](" "W, // ['I", "Love", "JavaScript"]
var s = "I$Love$ JavaScript”;
cfi[Link]([Link]”r("l‘-"}]i // ['T", "Love”, "JavaScript]

< Akshay Thakur />


< JSpiders BTM Layout />
/7 ! concat():
// Merges two or more strings into a new string.
/77 Syntax:
[Link](secondVariable, thirdVariable, ...);
I TEX:
var first = “Tata™;
var second = "Consultancy”;
var third = "Services'";
consolelog(first + " " + second + " ” + third); // "Tata Consultancy Services”
[Link]([Link](" ", second, " *, third)}; // "Tata Consultancy
Services”

/! indexOf():
// Returns the index of the first occurrence of a character
/7 7 Syntax:
[Link]("characterName');
JPExX
var s = "JavaScript”;
[Link]([Link]("am); // 1

i E] Iunl.r;dal@m:
// Returns the index of the last occurrence of a character.
/7 7 Syntax:
variableName lastIndexOf("characterName™);
JPEx
var s = "JavaScript”;
[Link]([Link]('a™)); // 3

/1 ! includes():
// Checks if a substring exists in the string and returns a boolean.
/7 7 Syntax:
[Link]("substring™);
JPEx
< Akshay Thakur />
< JSpiders BTM Layout /=
var s = "JavaScript”;
[Link]([Link]("a™)); // true
[Link]([Link]("b")); // false

J7 ! charAt():
// Returns the character at o specific index.
ff T Syntax:
[Link]{indexPosition];
N TEX
var s = "JavaScript”;
consolelog([Link](4)); // "S"

/7 ! charCodeAt():
// Returns the ASCII value of the character at a specific index.
ff T Syntax:
[Link]{indexPosition);
/M TEX:
var s = "JavaScript”;
[Link]([Link](1)); // 97

/7 ! [Link]():
/f Converts an ASCII code to a character.
ff T Syntax:

[Link](ASCII_number);
/M TEx:
consolelog{[Link](&5)); // "A"
[Link]([Link](97)); // "a”

< Akshay Thakur />


« JSpiders BTM Layout />
Array
Arrays

An array is a collection of homogeneous (same type) or heterogeneous


(different types) data elements.

Examples:

= [10, 20, 30, 40, S0]){homogeneocus)

= 10, "JovaScript”, null, true, 50.5){heterogensous);

Creation of Arrays
Arrays can be created in 2 ways:

2 Using new Keyword

1. Using Literals
Syntax: var arrayMome = [elementl, element?, ., elementNT;
Example:
var ar = [10, 20, 30, 40, 50];
[Link](ar); // [10, 20, 30, 40, 50]

2. Using new Keyword


Syntax: vor arayhlome = new Array();
Example:
wvar ar = new Array(}; // Creates an empty array
var ar= new Array(10, 20, 30, 40, 50); // Creates
an array with elements
[Link](ar); // [10, 20, 30, 40, 50]

Insertion in Arrays

= Akshay Thakur />


< JSpiders BTM Layout />
Inserticon is the process of odding elements into on array. Elements are
added based on indexing.
Exomple:
var ar =[], // Empty arroy
consoleloglary; // 1
ar[] = 10; /f Insert 10 of index 0
ar[1] = 20; /¢ Insert 20 ot index 1
or[2] = 30; // Insert 30 af index 2
console log(ar); // [10, 20, 30]

Modification in Arrays

Modification is the process of updating the elements present in an array.


Elements are modified based on indexing.
Exomple:
var ar =[10, 20, 30, 40, 50];
[Link](ar); /7 [10, 20, 30, 40, 50]
ar{1] = 200; /¢ Modify element o index 1
ar[2] = 300; // Modify element ot index 2
ar{4] = 500; // Madify element
ot index 4
consolejog(ar); // [10, 200, 500, 40, 500]

Deletion
in Arrays
Deletion is the process of removing elements from on array. Elements are
deleted using the delete keyword followed by the index.
Note: Deletion leaves empty ploces in the array.
Example:
war ar =[10, 20, 30, 40, 50];

[Link]), // [10, 20, 30, 40, 50]


delete ar[1]; // Delete slement ot index 1
delete ar[4]; // Delete element ot index 4
consolelog(ar]); // [10, empty, 30, 40, empty]
console log([Link]); // 5 (length remains the some)

< Akshay Thakur />


< JSpiders BTM Layout />
Advance loops on the Array
let nums = [30, 40, 50, 80];

for of loop
it will iterate through all the elements{values) of the array
for (let i of nums) {
[Link](i);

forin loop
it will iterate through the index of the array
for (let i in nums) {
[Link](i);
}

Array Methods

Mutable Methods (Modify the Original Array)


pep()
/f Syntax: [Link]()
Removes the last element from an array and returns it.
Example:
let arr =[1, 2, 3];
let lastElement = [Link](); // Remaves 3
[Link](arr); // [1, 2] {original array is modified)
[Link](lastElement); // 3 (removed element)

push()
// Syntax: [Link](elementl, element2, .., elemeniN)

< Akshay Thakur />


< JSpiders BTM Layout />
Adds one or more elements to the end of an array and returns the new
length.
Example:
let arr=[1, 2];
let newLength = [Link](3, 4); // Adds 3 and 4
consolelog(arn); // [1, 2, 3, 4] (original array is modified)
consolelog(newLength); // 4 (new length of the array)

shift()
£/ Syntax: [Link]()
Removes the first element from an array and returns it.
Example:
let arr = [1, 2, 3];
let firstElement = [Link](); // Removes 1
consolelog{arr); // [2, 3] (original array is modified)
consoleog(firstElement); // 1 (removed element)

unshift()
/{ Syntax: [Link](elementl, element2, .., elementi)
Adds one or more elements to the beginning of an array and returns the
new length.
Example:
let arr = [2, 3];
let newlLength = [Link](0, 1); // Adds 0 and 1
censolelog{arr), // [0, 1, 2,3] (original array is modified)
consolelog(newLength); // 4 (new length of the array)

splice0
/{ Syntax: [Link](startIndex, deleteCount, newElement1,
newElement2, .., newElementiN)
Adds or removes elements from an array at a specified index.
Example:
letarr = [1, 2, 3, 41;
< Akshay Thakur />
< JSpiders BTM Layout />
let removed = [Link](l, Z, 'd’, 'b?; // Removes 2 elements starting at
index 1, adds ‘a’ and b’
consolelog(arr); // [1, 'a’, "B, 4] (original array is modified)
consolelog(removed); // [2, 3] (removed elements)

sortQ)
//Syntax: sort{compareFunction)
= sort methed is to sort the array elements
e if we use sort method without compare function it will compare only
the first digits and it won't sort properly
e we can pass a compare function to sort method
//aoscending order
[Link]({a, b) =< {
returna- b;

B
//! descending order
[Link]({a, b) =< {
return b - a;

reverse()
/f Syntox: [Link]()
Reverses the order
of elements in an array in place.
Example:
letarr=[1, 2, 3];
[Link]();
conselelog(arr); // [3, 2, 1] {original array is modified)

copyWithin()
Jf Syntax: [Link](targetIndex, startIndex, endIndex)

< Akshey Thakur />


< JSpiders BTM Layout />
Copies a sequence of elements within the array to a specific position.
Example:
letarr=[1,2, 3, 4,5];
[Link](0, 3); // Copies elements from index 3 to the end and
pastes them starting at index 0
consolelog(arr); // [4, 5, 3, 4, 5] (original array is medified)

filly)
/¢ Syntax: [Link](value, startIndex, endIndex)
Fills all or part of an array with a static value.
Example:
letarr=[1,2 3, 4];
arr.fill0, 1, 3); // Fills with 0 from index 1 to3 (exclusive)
consolelog(arry; // [1, 0, 0, 4] (original array is modified)

Immutable Methods {Do Not Modify the Original Array)

at{index)
it will return the element present at a particular index ,
it also accepts negative index
let arr = [10, 20, 30, 10, 40, 50, 10];
[Link]([Link](2)); //30
[Link]([Link](-2)); //40
[Link]([Link](-4)); //20

arrindexOf(element)
it will return the index of a particular element
consolelog([Link](40)); //3
consolelog([Link](100)); //-1

lastIndexOf(element)
it will return the index of last occurence of the element
consolelog([Link](10));

< Akshay Thakur />


« JSpiders BTM Layout />
- concat()
/f Syntax: [Link]{arrayl, arrayZ, .., arrayMN)

Combines two or more arrays and returns a new array.


Example:
let arrl = [1, 21;
let arr2 = [3, 4];
let newArr = [Link]{arr2);

[Link](newarr); // [1, 2, 3, 4] (new array is created)


conselelog(arrl); // [1, 2] (original array remains unchanged)

slice()
Syntax: [Link](startIndex, endIndex)
Returns a copy of a portion of an array.
Example:
letarr=[1, 2,3, 4];
let sliced = [Link](1, 3); // Extracts elements from index 1 1o 2
consolelog(sliced); // [2, 3] (new array is created)
[Link](arr); // [1, 2, 3, 4] (original array remains unchanged)

join(separator)
it will join all the elements of the array and return a single string
it will return o new string
[Link]([Link](" ")); //grapes banana pineapple mango
consolelog([Link]("$")), //grapes$bananadpineapple$mango

Advance Methods
/7! find() , some() , every() , filter() , map() , forEach()
for all of these methods the callback function is same
callback Function ——»
» in that callback function we can pass three parameters ,

< Akshay Thakur />


< ISpiders BTM Layout />
# 1st parameter will be iterating variable (iterate through the
elements)
« 2nd parameter will iterate through index
* 3rd parameter represents actual array

find(callback fn....)
» callback function will be executed for every element until the
condition is satisfied (gets true).
® it will return that first element which satisfies the condition
letnums=[10,8
16,46 ,9 4,157
let res = [Link]((el , i , ar)=»{
[Link]("iteration : ", i+1)
return el»10;
// consolelog(el , i)
B
[Link](res)

some(callback fn...)
» callback function will be executed for every element until the
condition gets true.
# same is same as find only difference is it will return boolean values
» some will return true if any one element satisfies the condition
letnums=[10,8,16,6,9,
4 15];
let res = [Link]((el , i, arj=>{
consoledlog("iteration : ", i+1)
return elelf;
n
consolelog(res) // false

every(callback fn...)
< Akshay Thakur />
< JSpiders BTM Layout />
s every will return true if all the elements satisfies the condition
o if ony element is returning false for the condition there only it will
come out of the loop
® It will return boolean value
let nums = [10, 8, 14, &, 9, 4, 15];
let res = [Link]((el, i, ar) =» {
consolelog("iteration : ", i + 1);
return el <= 16;
s
consolelog(res); // frue

forEach(callback fn..)
it won't return anything it is just used to iterate only
let arr = [10, 21, 40, 90, 13];
[Link]({el, i, arr) =» {
consolelog(el, ij;

j2s

filter(callback fn...)
. Fflfer methed is used to filter out the array based on some condition
e it will return a new array , in that array all the elements satisfies the
condition will be there
e It does not change the eriginal array
let arr = [10, 21, 40, 90, 13];
let even = [Link]{{el, i) => {
return el % 2 === 0,
return f'_u_lse;

1A
let odd = arrfilter((el, i) =» el % 2 == D),
[Link](even);
consolelog(odd),

//! Assignment
< Akshay Thakur />
< JSpiders BTM Layout />
let names = ["varuni”, "akshay”, "aakash”, “pranav”, "aatul”, "shaubham™];
/7! filter the names with exactly 6 characters
/1! filter the names with exactly 3 vowel
/1! filter the elements starting with vowel

map(callback fn...)
// map method is used to transform each element of an array and create a new
arroy based on the returned values from the callback funcrion
A we have ta return a value from the collback function of the map, and that
value will be added to the new array. The actual array will not be modified
/7 map will accept a callback function, that callback function can have 3
parameaters
/11 15t porameter will be the iteration variable that will iterate through the values
of an array
/1 2nd parameter is for the indexes
/! 3rd parameter will represent the actual array
/f Example

letarr=[1,2 3, 4]
let newdrr = [Link]{el, ind, or) => {
return el 2;

i3
consoleloginewArr); // [2, 4, b, B]

reduce(callback fn...)
// reduce method is used 1o reduce the array 16 a single value
by executing a
collback function for each element (left to right)
/{ we have to return the accumulated value from the callback function of the
reduce. The octual array will not be modified
// reduce will accept a callback function, that callback function can have 4
parcmeters
/1 1st parameter is the accumulator, which accumulates the returned values

< Akshay Thakur />


< ISpiders
BTM Layout />
/! 2nd parameter is the iteration variable that will iterate through the values of
an array
/1" 3rd parameter
is for the indexes
/{1 4th parameter will represent
the actuol armay
// reduce also occepts an optional initial velue as the second argument
/# Example

lerarr=[1,23 4}
let sum = [Link]{{acc, el, ind, ar) => {
return ace + ek
b0y
consoleloag(sum); // 10

return el % 2Z===

B
console loglallEven); // true

reduceRight(callback fn..)
// reduceRight method is similar to reduce, but it processes the array from right
1o lefr
A/ we have to return the accumulated velue from the callback function of the
reduceRight. The actual array will not be modified
// reduceRight will accept a caollback function, that callback function can have 4
parameters
/! 1st parameter is the accumulator, which accumulotes the returned values
/1 2nd parameter is the iteration voriable that will iterate through the values of

an array
/1 3rd parameter is for the indexes
/1! 4th parameter will represent
the actual array
// reduceRight also occepts an optional initial value os the second argument
/i Example

letarr=[1,2 3 4%
let result = arrreduceRight{{acc, el, ind, ar) == {
return ace - el:

< Akshay Thakur />


« JSpiders
BTM Layout />
i2s
consolelog(result); // -2 (4-3-2-1)

Summary Table

Method Purpose Calibock Returns


Arguments

filter() Filters elements based (element, index, array) New array


on a condition

mapQ Transforms each {elemeant, index, array}) New array


element

reduce() Reduces array fo a {ocoumulator, element, Single value


single value (lefr-right) index, armay)

some() Checks if ot least one {element, index, array) Boolean


element passes a test

every(} Checks if all elements {element, index, array) Boolean


pass a test
find(} Finds the first element (element, index, array) Single element or
thaot passes a test undefined

reduceRight( Reduces array foa {occumulotor, element, Single value


) single value (right-left) index, array)

< Akshay Thakur />


< ISpiders BTM Layout />
What is an Object?
= An object is a collection of key-value pairs (properties).
= It is used to represent real-world entifies in a program.
= Keys ond value pair is called property, and values can be anything like
strings, numbers, booleans, functions, etc.

Creating an Object

e Object Literal Syntax (Most Common)


let person = 4
name: “Rohit”, — key ond volue are separated by colon (3)

age: 37,

team: "MI",
k

Rules for Keys:


e Keys can be strings, numbers, or symbols.
s If a key doesn't follow the rules of an identifier (e.g., starts with a
number or has special characters), it must be wrapped in quotes.
o If you use the same key more than once, the last value will
overwrite the previous one.

let marker = {
color: "Block”,

isMarried: frue,
77: "Dhioni”, // Number as o key

"leng*h™ 10, // Key with special chorocters

"Imarker™ "hey", // Key starting with a number

Accessing Object Properties

< Akshay Thakur />


= JSpiders BTM Layout />
1. Dot Notation (.):
Use the property name directly.
Example: [Link] — “John",
2. Bracket Notation {[ 1):
Use when the property name is dynamic or stored in a
variable.
Example: student["name™] — “"John".

Adding/Removing Properties
1. Add:
Use dot or bracket notation.
Example: [Link] = 20 or student{"age"] = 20.
2. Remove:
Use delete.
Example: delete [Link].

Object Methods
1. hosOwnProperty:
Check if a property exists.
Example: [Link]("nome”) — frue.
2. [Link]:
Get all keys in an array.
Example: [Link](student) — ["name”, "oge”].

Get all values in an array.


Example: Objectvaluesistudent) — [*Tohn”, 20].
4. [Link]:
Get key-value pairs as nested array.
Example: [Link](student) — [["name”, "John"], ["age”, 20]].

[Link]
Prevents adding or deleting properties but allows updating
existing ones.
const person = { nome: "Alice”, oge: 30 };
[Link](person);

< Akshay Thakur /=


< J5piders BTM Layout />
[Link] = 31; // Allowed
[Link] = "female™; // Not allowed
delete personnome; // Not allowed

&.[Link]
Prevents adding, deleting, or updating properties.
const car ={ brand: "Toyota”, model: "Comey” };
[Link]{car);

[Link] = "Corolia™, // Not allowed


[Link] = 2020; // Not allowed
delete carbrand; /7 Mot allowed

[Link]()

The [Link]() method checks if an object is sealed. It returns true if


the object is secled ond false otherwise.

[Link]()

The [Link]() method determines if an object is frozen. It returns frue if the


abject is frozen and false otherwise,

Ways to Create an Object in JavaScript


1. Object Literal

The simplest way to create an object using curly braces {:

letobj={

< Akshay Thakur />


< JSpiders BTM Layout />
name: "Peter Parker”,
age: 17,

oddress "Mew York”,

2. Object Constructor
Creates an empty object; properties can be added later.

let obj = new Object();

[Link]= 20;

[Link](akj); // {age: 20}

let obj2 = new Object({ age: 20, nome: "Rom” ),

consolelog{obi?); // {oge: 20, name: 'Ram’}

3. Constructor Function

Used to create multiple instances with similar properties.

function Student{name, age){


[Link] = name;
[Link] = oge;

b
let st1 = new Student("Pranav”, 20;
consolelog(stl); // Student {name: 'Pranav’, age: 20}

How new Works:

Creates an empty object {}.


ot

Assigns this to the new object.


Links the object's prototype.
Assigns possed arguments s properties.

< Akshay Thakur />


< JSpiders BTM Layout />
5. Rerurns the new object.

- filfid'lDr-l People(name, age) {

[Link] = name;
[Link] = age;

3
People prototype_ oddAge = function 0 {

consolejog([Link] + 100
K
let personi = new People{"Pranav”, 19}

[Link](); // 119

4. Class (ES6)

A cleaner way to define object blueprints, works similarly to constructor


functions.

closs Person {

constructor{name, agel {

[Link] = name;

[Link] = age;

oddAge() {

console log([Link] + 100);

let personl = new Person("Pranav”, 19},

console log{parsonly;

< Akshay Thakur />


« J5piders BTM Layout />
5. [Link]()

Copies properties from one aor more objects into a target object.

let objl = { name: "Pranav” };

let obj2 = { charocter: "sweet” };

consolelog{[Link]({}, objl, obj2)); /# { nome: 'Pranav’, charocter: ‘sweet”}

Creates a new object with a specified prototype.

let parentObj = {

name: "Atul”,

primtName{) {

consolefog({[Link]};

let obj = [Link]{parentObj);

console [Link]); #/ "Atul” (inherited)

[Link]()

Call ,Apply , Bind


In JavaScript, functions are objects that come with methods like call), apply(), and
bind() to explicitly set the this context, allowing for flexible function invecation
patterns.

1. callg) Method

< Akshay Thakur />


< JSpiders BTM Layout />
The call() method invokes a function immediately, setting its this context to a
specified object and passing arguments individually.

Syrtax:
[Link]{thisArg, argl, arg2, ...}

function infroduce(gresting) {
consolelogl” ${greeting}, I'm ${[Link]}.
}:
F

canst person = { name: “Alice” };

[Link]{person, "Hello"): // Output: Hello, I'm Alice.

In this example, introduce call{(person, 'Hello'y sets this to the person object and
passes ‘Hello' as an argument to the introduce function.

2. apply() Method

The apply() method is similar to call), but it ocoepts arguments as an array or


array-like object.

Syntax:

[Link](thisArg, [argl, arg2, .1}

function infroduce{greeting, punctuation) {

consoledog(* ${greeting}, I'm ${[Link]}${punctuation}


):
¥
const person = { name: "Bob" };

[Link](person, ["Hi", "I"]) // Qutput: Hi, I'm Bob!

Here, [Link]{person, ['Hi', "I'T) sets this to the person object and passes 'Hi'
and " as arguments to the infroduce function.

3. bind() Method

< Akshay Thakur />


< ISpiders BTM Layout />
The bind() method creates a new function that, when invoked, has ite this context
set to a specified object, with optional arguments pre-filled. This new function can
be colled later.

Syntax :

const boundFunction = [Link](thisArg, argl, arg2, )

function intreduce() {

consolelog(
I'm ${[Link]}.");

Example

~canst person = { name: “Charlie” };

const boundIntroduce = [Link]{person);

boundIntroduce(); // Qutput: I'm Charlie.

Math Object

Properties:

* [Link]: Represents the rotic


of the circumference of a circle to its diometer,
opproximately 3.14159.

s Math.SQRT1_Z Represents the square root of 1/2, opproximately 0.707.

» Math.S@RTZ Represents the square root of 2, approximately 1.414.

Methods:

+ [Link]{x) Returns the obsolute value of x. For example, [Link]{-%0) returns


20.

< Akshay Thakur />


< JSpiders BTM Layout />
[Link]{x): Rounds x down to the nearest integer. For example,
Math. floon(16.9) returns 1&,

[Link]{x): Rounds x up to the nearest integer. For example, [Link]{14.1)


returns 17.

Maothuround(x) Rounds x to the nearest integer. For example, [Link](18.5)


returns 17,

[Link]{x): Removes the froctional part of x, effectively truncating it. For


example, [Link]({16.7) returns 16.

[Link](): Generotes a pseudo-random number between 0 (inclusive) and 1


texclusive). For example, [Link]() might return 0.123456.

function getOtp(y

let otp = [Link]{Mathrondom(8999)+


1000;

return “Your OTP is ${otp}";

¥
consolelog{getOtp())

! Assignment --» Guessing Game , OTF Mathcing

Generating Random Mumbers in a Specific Range:

To generate o random integer between two values, you can use the following formula:

let min=1;

et mox = 10;

let randomValue = [Link]{[Link](} * (max - min + 13) + min;

consalelog(randomValue); /7 Outputs o randem integer between 1 and 10

< Akshay Thakur />


< JSpiders BTM Layout />
Date Object:

The Date cbject in JavaScript is used to work with dotes and times. You can create a
new date object using new Date(), which returns the current date and time.

Retrieving Date Components:

& getFullYear(): Retums the four-digit year (e.g., 2025).

» getMonth(): Returns the month (0-11). Jonuary is 0, February is 1, ond so on.

s getDofe(): Retums the day of the month {1-31).

+ getDay(): Returns the day of the week {0-8). Sunday is 0, Monday is 1, and so on.

s getHours(): Returns the hour {0-23).

» getMinutes(): Returns the minutes (0-59).

+ geiSeconds(): Returns the seconds (0-5%).

+ geiMilliseconds(): Returns the milliseconds (0-999).

Setting Date Components:

You can modify specific components of a dote using setter methods:

let purchoseDate = new Date();

[Link]{20207);

[Link]{8); /¢ September (months are B-indexed)

[Link]{15);

purchaseDate setHours{13);

[Link](30);

consolelog{purchoseDate); // Outputs: Tue Sep 15 2020 1330:00

< Akshay Thakur />


< JSpiders BTM Layout />
BOM(Browser Object Model)
BOM allows JavaScript to interact with the browser.

It controls things like window size, location, and history.


The window object is the main entry point for accessing BOM features.

BOM helps manipulote the browser environment outside the webpage.

Window Properties:
1. document
2. screen
3. history
4, navigator
5. location
6. innerheight
7. outerheight
8. innerwidth
9. outerwidth

[Link]:
It always represents the current html document. By using this, we can make
changes in the HTML document.

1 Screen:
It provides the basic information about the screen like height , width ,
arientation , etc..

3. History:
It will keep a track of web pages you opened and it will store as history. We
can perform forward() , back() operations using this.

4. Navigator:
It provides information about browser like appname , aversion , efc..

5. Location:

< Akshay Thakur />


< JSpiders BTM Layout />
It provides the basic information about the current location like path ,
hostname , href , etc..

&. InnerHeight:
It calculates the browser height excluding console area.

7. OuterHeight:
It calculates the browser height including console area.

E. Innerwidth:
It calculotes the browser width excluding console area.

9. Outerwidth:
It calculates the browser width including console area.

window methods:
. prompt()
R e
OB

. alert()
. confirm()
open()
. close()
. setTimeOut()
. setInterval()
=~

. clearTimeQut()
00

. cleatInterval()
0

L prompt():
It helps to take user input. It will display a popup message in the
browser.

-var userInput = prompt("Please enter your name:");

< Akshay Thakur />


< J5piders BTM Layout />
alert():
It will display a popup message with a button "OK"™.

alert{"This is an alert!™);

. confirm():
It will display
@ popup message with "OK"” & "CANCEL" buftons.

var result = confirm{"Do you want to continue?");

. open():
It helps to open a new webpage in a new tab.
[Link](“[Link] *_blank™);

. close():
It allows us to close the current webpage.

[Link]();

setTimeout():
It holds the execution until the completion of fime,
Syntax: setTimeout(callback_fn, timeourt);

setTimeout(() =»> alert("This message will appear after 3


seconds™), 3000);

. setInterval():
It will perform the same task multiple times with the time gap of
interval fime.
Syntax: setInterval{caliback_fn, intervalTime);

setInterval(() => alert("This will show every 5 seconds™), 5000);

. clearTimeout():
It will stop the werking of the setTimeout() method.

var timeoutId = setTimeout{() => alert{"This won't show™), 5000);

< Akshay Thakur />


< JSpiders BTM Layout />
clearTimeout{timeoutId); // This will cancel the timeout

9. clearInterval():
It will stop the working of the setInterval(Q method.
var intervalld = setInterval{() => alert{"This won't show
anymore”), S3000);

clearInterval(intervalld); /f This will cancel the interval

DOM (Document Object Model)

DOM stands for Document Object Made|


DOM is the part of the browser , which is used to manipulate the html elements , and
styles
DOM is a tree like hierarchical structure representing the html decument
It is created by the browser | because jovascript directly cannot communicate with
the html elements| so browser creates the dom where each and every html element
is converted to a node (object format)
Each HTML element becomes an element node, atiributes are attribute nodes, text
content forms text nodes, and comments are comment nodes.

< Akshay Thakur />


< JSpiders BTM Layout />

.
=) @

DOM Selectors
DOM selectors are used to target and access HTML elements in a document.
1. getElementById()
= Selects an element by its ID.

= Returns a single element.

= Syntox: [Link]{"idName");

2. getElementsByClassName()
= Selects elements by class name.

= Returns a collection (HTMLCollection) of matching elements.

< Akshay Thakur /=


« ISpiders BTM Layout />
s Syntox: [Link](
classMame™);

3. getElementsByTagName()
= Selects slements by tag name (e.q., div, p, hLL

= Returns a collection (HTMLCollection) of matching elements.

» Syntox: [Link]{"tagName");

4, getElementsByName()
= Selects elements by their name attribute.

= Returns a collection (NodeList) of matching elements,

s Syntox: [Link](
" name™);,

5. querySelector()
« Selects the first matching element based on an ID (#id), class (.class), or tag
(tag).

= Syntax: document. querySelector{"#idName / className / tagMame™);

&, querySelectorall)
s Selects all matching elements based on an 1D, class, or tag.

s Returns a MNodelist (which is not an array but can be looped through).

= Synto: [Link]{™#idName / classMame / tagName”);

Mote:
= getElementsByClassName(), getElementsByTagName(), and
getElementsByName() return collections, not actual arrays.

= These collections support indexing and iteration but do not support array
methods like push(), pop(), shift], ete.

CRUD Operations

< Akshay Thakur />


< JSpiders BTM Layout />
We can perform CRUD Operaticns on HTML Elements , HTML otftributes and
inline style

CRUD ON HTML Elements

AT g
I FATE
I e |
saETE
[ pR——
i etel

1. createElement(‘tag’)
Creates a new HTML element.

let variableName = [Link](”elementMame");

ler div = [Link]{"div");

2. append0
Appends content (text or nodes) 1o a parent element.

[Link]{content or node);

[Link](
This is Text Information™);
sectionoppend(div);

3, appendChild()

Appends only nodes to a parent element.

parentoppendChild(node);

[Link]{"This is Text Information™; // ¥ Error (Text must be a node)

< Akshay Thakur />


< J5piders BTM Layout />
[Link](div); /¢ B Works

4. textContent, innerText, innerHTML


Used to update the content inside an element.
s textContent and innerText display fext.
s innerHTML allows adding HTML tags.

[Link] = "content”;
selectorinnerText = "cantent";
selectorinnerHTML = "cb>This is contente /b’ ", /i Allows HTML

[Link] = "This is content”;


[Link] = "This is content”;
divinnerHTML = "<b>This is content</bs",

5. replaceChild()
Reploces an existing node with o new node.
porent reploceChild{newMode, oldMode);
[Link]{hl, divy;

&. removeChild()
Removes a child node from a parent element.

[Link](node);
sectionremoveChild(hl);

< Akshay Thakur />


< J5piders BTM Layout />
CRUD ON HTML Attributes

cEra
! )
| e L
i~ P ml
[ edliributel}
sl el } _] it TR |i [ eeaserltl
— ] [I wmmeireriments
e
———
|
-_

1. setAttribute():
It will add a new attribute to the alement.
If the attribute is alreody present it will update the
attribute value.
/12 Syntax:
[Link]("attributeName™,"attributeValua™)
7 Ex:
[Link]("id" "dema"y;

It will return the attribute volue of an element.


/2 Syntax:
[Link]
Attribute attributeName")
/R Ex
[Link]™y; /f dema

3. removeAtiribute():
It will remove the existing attribute of an element.
/#7 Syntax:
[Link]("atiributeNome")
fREx
[Link]("id™)

< Akshay Thakur />


« JSpiders BTM Layout />
CRUD ON CSS Styles

s srpe J
N

.u!—:l -Llr_ LIUIAI 3 u';Li


) ” y
1. setPropertyl [ getFropartyvaiue :J 1. 5etPrapercyl) remnvaf'upzr(y
2. prupartytane e — 1. prapescylons
[Link] |3 osaTest J

1. setProperty(), propertyName, cssText


These methods are used to add CSS properties to an element:
setProperty() and propertyName allow adding one property at a time.
cssText allows odding multiple properties at once, but it overwrites existing
styles.

selectorstylesetProperty("property-nome”, "property-value"y;
selectorstyle propertyMome = "propertyVolue”;
selector [Link] = "propertyl: valuel; property2 volue2; _.";

[Link] setProperty(“font-size”, "$0px™); /f Using setFroperty()


[Link] = "40px"; // Using propertyNome
[Link] = "font-size: 40px; color: red;”; // Using cssText

2. getPropertyValue()
Used to refrieve the value of a €SS property from an element.

[Link]{"property-name”);

[Link]("font-size™); // Returns "40px"

3. removeProperty()
Used to remove a spacific CSS property from an element.

[Link] Property("property-name”);

[Link]("font-size™); // Removes font-size property

< Akehay Thakur />


< JSpiders BTM Layout />
Events in JavaScript
Events are actions friggered by the browser or user (e.g,, clicking a button, pressing
a key, resizing a window, etfc).

Mouse Events Key Events Farm Events Window Events


click keypress submit laad
dilelick keydown reset resize
MOUSELR heyup facus serall
mousedown blur
mouseaver change
mouseout
maousemove
contentmeny

Ways to Attach Events in JavaScript


Wa con attach events to an HTML element in three ways:
1 HTMLAtributes
2 DOMProperties
3. addEventListiners

1. Using HTML Attributes


Here, the event is assigned directly as an attribute in the HTML tag.

<tagname onEventMames="JavaScript Code"sContent</ tagnames;


<div onclick="olert{'Click Event is triggerad)">Click Me< /divs;

2. Using DOM Properties


Here, we attach events using JavaScript properties.

[Link] = function;

let div = [Link]


By Id{"myDiv"™);
[Link] = function () {
[Link] = "color: white; background-color: teal; border: Lpx solid; text-align:
oenter,™

3. Using addEventListener()
This is the best and most flexible way to attach events,

< Akshay Thakur />


« JSpiders BTM Layout />
= We can attach multiple functions to the same event.
= We can remove the event later using removeEventListener().
s It supports event propagation.

[Link]{"eventMame”, function, useCapture);

let button = document,get


Element By Id{"myButton™);

[Link]{"dick”, (}=> {
consoledog("Click Event is Triggered™);
24

Understanding the Third Parameter in addEventListener()


The third parometer (useCopture) is optional and controls event propagation:
s frue
— Capturing phose (event runs from parent to child)
= false — Bubbling phaose (event runs from child to parent, default behavior)

Event Propagation
Event propagation refers to how events flow through the DOM hierarchy when an
event ocours, It consists of three phases:

1 T
I DOCLIMENT

l HTHL

Event Capturing Event Bubbling


(Prease 1) I i {Phasa 3)

(=1

BUTTDMN |

Ewent Target
(Phase Z)

1. Capturing Phase (Event Capturing/Trickling)


= The event starts from the window and travels down to the target
element.

2. Target Phase (Event Execution)

« Akshay Thakur />


< JSpiders BTM Layout />
= The event reaches the target element and executes its handler.

3. Bubbling Phase (Event Bubbling)


= The event bubbles up from the target elemant to the window.

Example

[Link]{ "click”, { =» {
[Link]("Parent Clicked™);
}. true ¥; /f Copturing mode

[Link]"click™,(} == {

consolelog("Child Clicked"y,
htrue ); /f Capturing mode

[Link]( "click”, 0 =» {
consolelog("Parent Clicked™);
t. falsey; // bubbling mode

[Link]"click™,(} =5 {
consolelog("Child Clicked™);

}.fatse ); /f bubbling mode

Event Object
The event object (event or e) is an automatically passed argument to the event
handler function, when an event occurs in JavaSeript. It contains details about the
event, such as the type of event, the targat element, mouse coordinates, key
presses, and more.

[Link]{"bin"LaddEventListener{"click”, function (e} {


[Link](e); // Logs the event object to the console
}21

[Link]()
You use preventDefoult() when you want to stop a default browser behavior, such as:
1. Stopping form submission
1. Preventing link navigation
3. Disabling right-click menu

= Akshay Thakur />


< JSpiders BTM Layout />
Stopping form submission

[Link]{"myForm™[Link]("submit”, function (e) {


[Link](); // Stops the form from reloading the page
olert{"Form submissicn prevented!™);
35

+ Without preventDefauli(): The form will submit and relood the page.
+ With preventDefoult(): The form won't submit, allowing JavaScript validation.

Promises{ES6)

A promise in JavaScript is an object representing the eventual


result of an asynchronous operation.

It acts as a placeholder for a value that may not be


immediately available. Promises help manage asynchronous
code
let myPromise = new Promise({resolve, reject) =» {
let success = true; // Simulating success or failure
setTimeout(() == {
if {(success) {
resalve("Promise Resolved Successfully!™);

petse |
reject{"Promise Rejectedr,;
}
}, 2000);
B

State Of Promise

A promise is in One Of these States

= pending: initial state, neither fulfilled nor rejected,

« Akshay Thakur />


< JSpiders BTM Layout />
= fulfilled: meaning that the speration was completed successfully.
= rejected: meaning that the operation failed.

aspneacions

asbail J/
-
pandeg il [Rentenfuminarsy YS
e pning
_ maniy -
Fromes —_— ___.L Prormis . i
_ mje el acPaeden)] T J
T Loy | T

Handling a Promise

#To hondle promises


we have some instance methods

= then(): hondles resalved state


» catchQ: handles rejected state
= finally{) : will be executed in either resclved or rejected state

myPromise

Athen{message => [Link]{"Success:", message))

wcatch{error
=» consolelog{"Error:", error))

Finaliy(() => console log(“Promise Completed!"});

Chaining Promises

Each .then(} returns o new Promise, allowing chaining.

If we return anything from then block it will be wropped ogain in a promise so to handle
that we have to use one more then block.

let chainPromise = new Promize{resolve =»{

satTimeout(() => resolve({10), 10007;

B
< Akshay Thakur />
< JSpiders BTM Layout />
chainPromise then{num =» {

console log{numy); // 10

return num * Z;
n
Ahenf{num =s {

consolefog{numy: // 20

return num *3;

n
dthen{num == {

console log{num}: // 60

< Akshay Thakur />


< JSpiders BTM Layout />

You might also like