JavaScript M8 Notes
JavaScript M8 Notes
JavaScript
JavaScript is a high-level scripting language used to create
interactive and dynamic web pages.
Characteristics of JS
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.
ommuni srporations
on Eich (1995)
Mocha
aScript
ECMASCcript
Mocha.
» Mocha was later renamed LiveScript, and then finolly JavaScript .
= 1In 1997, JovaScript was standardized os ECMAScript (ES) by ECMA
Internatienal.
= ES6 (2015) — Added let, const, arrow functions, classes, and many
iy / >
« JSpiders BTM Layout />
Java v/s JavaScript
Java JavaScript
Programming language Programming and Scripting
language
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
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.
Machine
Code
C. Execution
Heap.
- : memary
Execution
N — i
context -
e
_ ]
- ™
CALL STACK HEAP
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
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");
<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.
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
Identifiers
Literals
L wvar
2 let
5. Const
Declaration v o x
Initialization v v *
Re-declaration v x *
Re-initialization v < x
Declaration +
Initialization v 4 <
let b; fideclaration
b =40; // init
let bl = 30; /f dec+init;
let b1; flredeclaration is not possible
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);
let by // declaration
b =30; // initialization
b = 40; //re-initialization
let bl = 50; // declaration+initialization
/#let bl; // re declaration is not possible
p—= Lnainfinad
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)
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
let and const are hoisted but remain in the Temporal Dead Zone unil
initialized.
let a = 10;
Data Types
Data types specify the type of values stored in variables)\
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)
Logical Operators:
» GE(AND)
* [ (OR)
s [(NOT)
Ternary Operator:
Conditional Statements
Conditional statements execute specific code blocks based on conditions.
1. if Statement
Syntax:
i (eondition) {
/{ Code to execute
+
2. if-else Statement
Syntax:
if (condition) {
[/ 1f block code
}else {
/{ Else block code
}
Syntax:
if (conditionl) {
/f Code block 1
} else if (conditionZ) {
/f Code block 2
}else {
/¢ Default block
1
4. Nested if
Syntax:
if {conditionl) {
if (condition2) {
/i Nested if code
}
1
5. switch Statement
Syntax:
switch (expression) {
case valuel:
/f Code for casel
break;
case value2:
// Code for case2
break;
default:
/f Default case
LLogical operators
false
0 {and -0)
On (BigInt zero)
™ {empty string)
null
undefined
NaM
if {money) {
}else{
consolelog("you should get a job™);
Type Conversion
== - 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
Syntax:
letii =1;
while (i <= 5] 1
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) ;
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.
Syntax:
leti=1; // Initialization
do{
Function
A function is a reusable block of code that performs a specific task when invoked.
Functions improve code readability, maintainability, and efficiency.
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,
Return Statement
Example:
Function Invocation
yFunetion(10, 2)
Example:
Types Of Functions
1. Named Function
2. Anonymous Function
3. First Class 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) {
}
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
L
greet(};
4. Function Expression:
An expression of storing any function into a variable (already covered in
anonymous functions).
// ? Syntax:
{function () {
// Code
o
J/ 7 Example 1:
(function (a, b) {
[Link](a + b);
110, 20; /¥ 50
consolelog(s(107); // 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.
function higherOrder(fn) {
[Link]("Before executing callback™);
fn();
consolelog("After executing callback™);
}
B. Callback Function:
A function passed as an argument to another function is called as
callback function
function sum(a, b) {
return o + b;
}
function sub(a, b) {
return a - b;
}
function mui(a, b) {
return a * b;
}
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;
Ex 2
function outerFunction(x) {
function innerFunction(y) {
return x + y;
3
return innerFunction;
b
function counter() {
let count = 0;
return function getCount() {
[Link](++count);
}
let rescounter = counter()
rescounter() // 1
rescounter() //2
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:
’
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”
/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"
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]
/! 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”
Examples:
Creation of Arrays
Arrays can be created in 2 ways:
1. Using Literals
Syntax: var arrayMome = [elementl, element?, ., elementNT;
Example:
var ar = [10, 20, 30, 40, 50];
[Link](ar); // [10, 20, 30, 40, 50]
Insertion in Arrays
Modification in Arrays
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];
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
push()
// Syntax: [Link](elementl, element2, .., elemeniN)
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)
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)
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));
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 ,
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
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:
Summary Table
Creating an Object
age: 37,
team: "MI",
k
let marker = {
color: "Block”,
isMarried: frue,
77: "Dhioni”, // Number as o key
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”].
[Link]
Prevents adding or deleting properties but allows updating
existing ones.
const person = { nome: "Alice”, oge: 30 };
[Link](person);
&.[Link]
Prevents adding, deleting, or updating properties.
const car ={ brand: "Toyota”, model: "Comey” };
[Link]{car);
[Link]()
[Link]()
letobj={
2. Object Constructor
Creates an empty object; properties can be added later.
[Link]= 20;
3. Constructor Function
b
let st1 = new Student("Pranav”, 20;
consolelog(stl); // Student {name: 'Pranav’, age: 20}
[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)
closs Person {
constructor{name, agel {
[Link] = name;
[Link] = age;
oddAge() {
console log{parsonly;
Copies properties from one aor more objects into a target object.
let parentObj = {
name: "Atul”,
primtName{) {
consolefog({[Link]};
[Link]()
1. callg) Method
Syrtax:
[Link]{thisArg, argl, arg2, ...}
function infroduce(gresting) {
consolelogl” ${greeting}, I'm ${[Link]}.
}:
F
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
Syntax:
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
Syntax :
function intreduce() {
consolelog(
I'm ${[Link]}.");
Example
Math Object
Properties:
Methods:
function getOtp(y
¥
consolelog{getOtp())
To generate o random integer between two values, you can use the following formula:
let min=1;
et mox = 10;
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.
+ getDay(): Returns the day of the week {0-8). Sunday is 0, Monday is 1, and so on.
[Link]{20207);
[Link]{15);
purchaseDate setHours{13);
[Link](30);
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:
&. 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.
alert{"This is an alert!™);
. confirm():
It will display
@ popup message with "OK"” & "CANCEL" buftons.
. 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);
. setInterval():
It will perform the same task multiple times with the time gap of
interval fime.
Syntax: setInterval{caliback_fn, intervalTime);
. clearTimeout():
It will stop the werking of the setTimeout() method.
9. clearInterval():
It will stop the working of the setInterval(Q method.
var intervalld = setInterval{() => alert{"This won't show
anymore”), S3000);
DOM Selectors
DOM selectors are used to target and access HTML elements in a document.
1. getElementById()
= Selects an element by its ID.
= Syntox: [Link]{"idName");
2. getElementsByClassName()
= Selects elements by class name.
3. getElementsByTagName()
= Selects slements by tag name (e.q., div, p, hLL
» Syntox: [Link]{"tagName");
4, getElementsByName()
= Selects elements by their name attribute.
s Syntox: [Link](
" name™);,
5. querySelector()
« Selects the first matching element based on an ID (#id), class (.class), or tag
(tag).
&, querySelectorall)
s Selects all matching elements based on an 1D, class, or tag.
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
AT g
I FATE
I e |
saETE
[ pR——
i etel
1. createElement(‘tag’)
Creates a new HTML element.
2. append0
Appends content (text or nodes) 1o a parent element.
[Link]{content or node);
[Link](
This is Text Information™);
sectionoppend(div);
3, appendChild()
parentoppendChild(node);
[Link] = "content”;
selectorinnerText = "cantent";
selectorinnerHTML = "cb>This is contente /b’ ", /i Allows HTML
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);
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;
3. removeAtiribute():
It will remove the existing attribute of an element.
/#7 Syntax:
[Link]("atiributeNome")
fREx
[Link]("id™)
s srpe J
N
selectorstylesetProperty("property-nome”, "property-value"y;
selectorstyle propertyMome = "propertyVolue”;
selector [Link] = "propertyl: valuel; property2 volue2; _.";
2. getPropertyValue()
Used to refrieve the value of a €SS property from an element.
[Link]{"property-name”);
3. removeProperty()
Used to remove a spacific CSS property from an element.
[Link] Property("property-name”);
[Link] = function;
3. Using addEventListener()
This is the best and most flexible way to attach events,
[Link]{"dick”, (}=> {
consoledog("Click Event is Triggered™);
24
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
(=1
BUTTDMN |
Ewent Target
(Phase Z)
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™);
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]()
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
+ Without preventDefauli(): The form will submit and relood the page.
+ With preventDefoult(): The form won't submit, allowing JavaScript validation.
Promises{ES6)
petse |
reject{"Promise Rejectedr,;
}
}, 2000);
B
State Of Promise
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
myPromise
wcatch{error
=» consolelog{"Error:", error))
Chaining Promises
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.
B
< Akshay Thakur />
< JSpiders BTM Layout />
chainPromise then{num =» {
console log{numy); // 10
return num * Z;
n
Ahenf{num =s {
consolefog{numy: // 20
n
dthen{num == {
console log{num}: // 60