0% found this document useful (0 votes)
20 views

Java Script

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Java Script

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 29

For my reference :

chapter 1. Basics
Chapter 2 : Variables & Datatypes
Chapter 3 : Operators & Conditions
Chapter 4 : Arrays
Chapter 5 : Loops
Chapter 6 : Functions
Chapter 7 : Strings
Chapter 8 : DOM
Chapter 9 : Error Handling
Chapter 10 : Objects
Chapter 11 :
Events

**Convertion code into machine code is pending***


**This keyword is pending

1. what is Javascript? what is the role of JS engine?


---javaScript is a programming language that is using for converting static web
pages to interactive and dynamice web pages

Key Features of JavaScript:


Interpreted Language: JavaScript code is executed line-by-line by the browser's
JavaScript engine without needing prior compilation.
Dynamic Typing: Variables in JavaScript can hold any type of data and can change
type at runtime.
Event-Driven: JavaScript is often used to respond to user actions like clicks, form
submissions, and other events.
Object-Oriented: JavaScript supports object-oriented programming with prototypes
and classes.
Asynchronous Programming: JavaScript supports asynchronous operations, allowing for
non-blocking code execution with techniques like callbacks, promises, and
async/await.

--- A javsScript engine is a program present in web browser that exectutes


javaScript code
ex
javaScirpt engine
V8 in chrome
sprider Monkey in FireFox
chakra in edge
Javascript Core in safari

2 What are Client side and Server side?


--A client is a device application, or software component that requets and consumes
service or resources from a server
--A client is a device,computer,or Software application that provides
service,resources,for functions to clients

3 What is Scope in JS?


Scope determine where varibales are determined and where they are accessed.
Three types of scopes
1. Global Scope
2. Functional Scope
3. Local Scope

example
let globalVaribale="global" //global
greet();
function greet(){

let functionVariable="function" //function


if(true){

let blockVariables="block"; //block

Q4. what is the type of a variable in JS when it is declared without using var,let
or const keywords ?
by default var is declared without any type is defined
if(true){
variable=10;
}
console.log(vairable) //10

5 What is Hoisting in Javascript?


hoisting is a javaScript behaviour where functions and vairbales declaration are
moved to the top of their
respective scopes during the compilation phase

example
//function hoisting
myfunction();

function myfunction(){
console.log("Hello");
}

//variable hoisting
x=10;
console.log(x);
var x;

6 What is JSON?

JSON(javaScript OBject Notation ) is a lightweight data interchange format.


JSON consists of key-value paris.

it's a Langue in which UI/Client interact

**********Chapter 2 : Variables & Datatypes******

7 What are variables? var vs let vs const.


variables are used to store data
var is functional scope and let,const is block

function example(){

if(true){

var count=10;
console.log(count);
}
console.log(count); // it will access it

let creates block scoped vairiables


using let

function example(){
if(true){
let count=10;
console.log(count);
}
console.log(count); //Not accessible

const can be assigned only once,and its value cannot be changed afterwards.
const z=10;
z=20;

console.log(z)

8 What are data types in JS?


let age=25 Number Type
let message='Hello' String

let isTrue=ture; boolean

let x;
console.log(x) undefined

let y=null;
console.log(y) null

Types

primative and Non Primitives


Number Objects
Strings Array
Booleans Function
undefined Date
Null RegExp

primitive can hold sing value non primitive can hold multiple values

9 what is the difference between primitive and non-primitive data types?


Types of Data Types
primative and Non Primitives
Number Objects
Strings Array
Booleans Function
undefined Date
Null RegExp
Primitive data type can hold only Single value;
Primitive data tyes are immutable

let age=25;
age=30 (it will create new memory 25 will still remain in memory)

Non Primitive
They can hold multiple values
They are mutable and their values can be changed
let oddNumbers=[1,2,3];
let person={
name:"john"
}

10 what is the difference between null and undefined in JS?


let undefinedVarible
console.log(undefinedVariable);

1.undefined:when a variable is decleared but has not been assigned a values,it is


automatically initialized with undefiend

2. null: null vairbles are intentionally assigned the null value

3. undefined: can be used when you don't have the value right now but you will get
it after some logic or operation

4. null: can be used when you are sure you do not have any value for the particular
variables

11 what is the use of typeof operator?


typeof vairable used to determine the type of each variable
let num=42; typeof num //number
let str='Hellow world';//string
let bool=true; //boolean
let obj={key:"value"} //object
let arr=[1,2,3]; //object
let fun=function(){} ///function
type of undefinedVariable ->undefined
type of null is object

12 what is type coercion in JS?


it is automatic conversion of values from one data type to another during certain
operations or comparision

uses
Type coercion can be used during String and numbers concatenations
Type cerscion can be used while using Comparison operators
let string="42"
let number =42
let boolean =true;
let nullValue=null;

console.log(string+number) //"4242"
cosole.log(number+boolean) 43
console.log(number==string) true
console.log(boolean==1)
console.log(boolean +nullValue) Output 1

********Operators & Conditions

13 what is operator precedence? Types


As per operator precedence,operators with higher precedence are evaluated first.
BODMAS
result=a+b*c+(a-b);

14 Unary vs Binary vs Ternary operators.


Unary

let a=5;
let b=-a;
++a;

Binary

let x=10;
let y=3
x+y; two operands

Ternary
let result =condition?'YES':'NO';

15 What is short-circuit evaluation in JS?


Shor-circuit evaluation stops the execution as soon as result can be determined
without evalutation the remaining sub-expressions

let result=false && someFunction() if first conditon true then return second

let result2=true|| someFunction(); if first is true return first only and if first
is false then only return second

16 Conditional Statement Types.


if/else
ternary
switch
17 Double equals == vs === Triple equals
== operator compares two values for equality after performing type coersion
=== compares two values equality without performing type cerscion

some examples
null==undefined is true
null===undefined is false
console.log(0 == false); //true
console.log(0 === false); //false
console.log('0' == false); //true
console.log('0' === false); //false

let a = 10;
let b = "10";
console.log([] == []); //false because both are array and creates new space in
memory
console.log(a === b); // false
NaN==NaN false //it is not equal to itself even it is denoting not a number?
{} == {} //false both object create new space in memeory ?

console.log(' \t\r\n' == 0) //true it is demoting a empty space when empty


space convert it become 0;

18 Spread operator and Rest operator in JS


spread Operator
it is used to expand or spread elements for an iterable into individaul elements

const array=[1,2,3]
console.log(...array);
uses
1. copying array
const original=[1,2,3];
const copiedArray=[...original];
console.log(copiedArray);

2. Merging

const array1=[1,2,3];
const arrays=[4,5]
const mergedArray=[...array1,...array];
console.log(mergedArray);

3. Passing multiple arguments

const number=[1,2,3,4,5];
sum(...numbers);
function(a,b,c,d,e){
console.log(a+b+c+d+e);
}

****REST

it is used in function parameters to collect all remaining arguments into an array


display(1,2,3,4,5)

function display(first,second, ...restArguments){


consol.log(first);
conseol.log(second)'
console.log(remaining) // [3,4,5]

************Arrays*************
19 what are arrays in JS? How to insert, remove, access, sort, reverse and
manipulate array elements?
An array is a data type that allows you to store multivalue in a single variable

Methods
Get
Add
remove
modify

**indexOf()
const array=[1,2,3,4]
let a=array.indexOf(3); //2

***find() and filter()


const array=[1,2,3,4]
let c=array.find((num))=> num%2==0;
it returen first elemenet which satisfy condition

**filter()
let d=array.filter((num)=>num%2==0);
output =[2,4];

**slice()
const array=["a","b","c","d","e"];

get subset of array from start index to end index

array.slice(1,4);
output // [b ,c d]

***push() vs concat()
push() method modify the original array itself

let array=[1,2];
array.push(3.4);
console.log(array) // [1,2,3,4]

**concat()
it will create new array not modify actual array
let array=[5,6];
let array3=array.concat(7,8);
console.log(array3)

**pop() vs shift()
pop() will remove last elemtent and shif remove first element
arr1=[1,2,3,4];
let popped=arr2.pop();
console.log(popped);

******splice() //TODO

it can add,remove,or replace

array.splice(startIndex,deleteCount, ...itemToAdd);

let letters=['a','b','c'];
letters.splice(1,0,'x','y'];
console.log(letters) => output a,x,y,b,c

***map() vs forEach()

arr=[1,2,3]
let mapArray=arr1.map((e)=>e*2);

console.log(mapArray);
map() method is used when you want to modify each element of an array
and create a new array
**forEach()

let arr2=[1,2,3];
arr2.forEach((e)=>{
console.log(e*2);
});
console.log(arr2);
forEach() method is used when you want to perform some operation on each element of
an array without creating new array

***sort and reverse an array

let array=[1,2,3,4]
array.sort();
conole.log(array);

array.reverse();
console.log(array);

20 what is Array Destructing in JS?


array Destructing allows you to extract element from an array and assign them to
indivual variables

const fruits=['apple','banna','orange'];

const [first,second,third]=fruits;

21 what are array-like objects in JS?


array like objects are objects that have indexed elements and a lenght property,
similar to array
but they may not have all methods like push ,pop() and other

example of String
const str="HEllo"

console.log(str) output hello


console.log(str.length); // 5
console.log(str[0]) outptu H

it works somewhat like array but it is String but not exactly an array

22 How to convert an array-like object into an array?


Array.from()
const str = "Hello, World!";
const arr = Array.from(str);

console.log(arr);
// Output: ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d", "!"]

spread

const str = "Hello, World!";


const arr = [...str];
console.log(arr);
// Output: ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d", "!"]

*******Loops******

23 what are loops? what are the types of loops in JS?


A loop is a programming way to run a piece of code repeately

Types
for
while
do-while
for....of
for..in

for(int i=0;i<5;i++){
}

let j=0;
while(j<5){
j++;
}

***while vs do while
***break and continue

24 what is the difference between for and for..of loops in JS?


// can search more
for loop is more complex
for..of is more easy
for(let val of arr){
}

25 what is the difference between for..of and for..in loops in JS?

for..of loop is used to loop throught values of objects like arrays,strings

for-in loop

loops over the object

const person={
name:"happy"
}

for(let key in person){


console.log(person[key]);
}
26 what is forEach loop? Compare it with the above methods.
forEach can iterate over objects as well lilke

const person={
name:"happy"
}
Object.values(person).forEach(value=>{
});
for of loop

for(let item of array){


conosle

if(item==2){
break;
}
}

array.forEach(function(item){
console.log(item);
if(item==2){
break; //error
}
});

**********************Functions********************

27 what are Functions in JS? what are the types of functions?


function is a reusable block of code that perform specific task

Types
Named function
Anonymous Function
Funciton Expression
Arrow Function
IIFE
Callback Function
Higher order Function

1. Named and annonymou function


Named Function have a name identifier
used it for big and complex logic
use when you wan to reuse it
function sum(a,b){
return a+b;
};

Anonymouos
it does not have name
use it for small logics
use when you want to use a funciton in single place
console.log(function(a,b){
return a*b;
}(4,5));

Function Expression
A function expression is a way to defin a funciton by assigning it to a variable
const add=function(a,b){
return a+b;
};

Arrow Function
Arrow function, also now as fat arrow function,is a simpler and shorter way for
defining functions in JS
example
const add=(x,y)=>x+y;
what is a callBack Function? what is it use ?
A callBack function is a function that is passed as an argument to another function

function add(x,y){
return x+y;
}
function display(x,y,operation){
var result=operation(x,y);
console.log(result);
}
display(10,5,add);

Higher order function


in above display function which is receiving a callback function as an argument is
higer order function
and return function as a result

ex

function hof(func){
func();
}
hof(sayHello);
function sayHello(){
console.log("hello");
}

function createAdder(number){
return fucntion(value){
return value+number;
};
}

const addFive=createAdder(5);
console.log(addFive(2));
****what is it's use ?

search it

28 what is the difference between arguments and parameters?

function add(a,b){ // placeholders are parameters


console.log(a+b);
}

add(3,4) //arguments actual values

***ways to pass arguments to a function


1.position Argument ->General way
2. Named Argument

var person{
name:"happy"
}
function greet(person){
console.log(person.name);
}
greet(person)

3. Arguments Object

sum(1,2,3);

function sum(){
console.log(arguments{0]);
console.log(arguments[1]);
console.log(arguments[2]);

till 3 we can use only

29 Default Parameters in functions in JS.


function greet(name="happy")
{
console.log(name);
}
greet(); //output happy bcz default

greet("amit") // output amit it will ovveride


30 what is the use of event handling in JS?
Event handling is the process of responding to user action in a web page

addEventListener method of JS allows to attach an event name and with the function
you want to perfomn on that event

ex

<button id="myButton">Click me</button>

const button=document.getElementById("myButton");
button.addEventListener('click',function(){
alert('button clicked!');
});

Types of events
1. click
2. mouseover
3.keydown
4.keyup
5.submit
6.focus
7.blur
8.change
9.load
10.resize

31 what are First-Class functions in JS?


A programming lanugage is said to have first-class functions if functions in that
language are treated like variables
IN JS Function can be treated like
1.passing as argument
2.return as value
3.assign as a variable
32 what are Pure and Impure functions in JS?
A pure function is a function that always produce the same output for same input

impure function:- proudces different output for same input


33 what is Function Currying in JS?
currying in JS transform a function with multiple argumetns into a nested series of
functions each taking a single argument
function multiple(a,b){
return a*b;
}
function carriedMuliply(a){
return function(b){
return a*b;
};
}

const double=curriedMutiply(2);
console.log(double(5));

Advantage :-Reusabliit,modularit and specialization


34 call() & apply() & bind() methods in JS?
check on Google

************Strings************
34 what is a string?
var str="String"
it is a data type used to store and manipulate data

35 Template Literals and String Interpolation


`${Template}`

var myname="Happy"
var str3=`hello ${myname}`;
console.log(str3);

it is also know as template string, is a feature introduced in ECMAScript 2015 for


string interpolation and mulitline strings in JS

36 single quotes vs double quotes vs backticks


single and double quotes are same
backticks for string literal

37 String Operations in JS
add
let str1="hello"
let str2="world";
let result=str1+" "+str2;

concat()
let result2=str1.concat(" ",str2);

extract portion

let subString=result.substring(6,11);
console.log(subString);
Retrive length
result.length

uppercase

result.toUpperCase()
result.toLowerCase();

split a string into an array of substring

let arr=resut.split(" ");


console.log(arr) ["hello","world"];

replace

result.replace('world","JAvaScript");

remove leading and trailing whitespace

let str=" Hellow World ";


let trimmedStr=str.trim();
console.log(trimmedStr);

38 what is string immutability?


Strings in JS are considered immutable bcause you cannot modify the content of an
existing string directly.

39 Different ways to concatenate strings in JS


4 ways

with +
with concat()
with template literal
let r3=`${s1} ${s2}`;

with join
let strings =[s1,s2];
let r4=strings.join(' ');

******************DOM****************
40 what is DOM? what is the difference between HTML and DOM?
DOM represent the web page as a tree like structure that allows JS to dynamically
access and manipulate the content and structure of a web page

41 How do you select, modify, or remove DOM elements?


42 Selectors in JS DOM.
Selectors in JS help to get specific elements from DOM based on Ids,class names,tag
names.
getElementById()
getElementByClassName()
getElementsByTagName()
querySelector()
querySlectorAll()

getElementById vs getElementByClassName vs getElementByTagName


querySelect vs querySelectorAll

43 what are the methods to manipulate elements, properties and attributes of JS


DOM?
1.textContent
2.innerHtml
3.setAttribute
4.removeAttribute
5style.setProperty
6 classList.ad()
44 what is the difference between innerHTML vs textContent?
example
<div id="myElement1>Hello</div>
<div id="myElement2>World</div>

var element1=document.getElementById("myElement1");
element1.textContent="<strong>Happy</strong>"

output <strong>Happy</strong>

var element1=document.getElementById("myElement2");
element1.innerHtml="<strong>Happy</strong>"

output Happy

45 How to add or remove properties of HTML elements from the DOM using JS?
1.setAttribute
<!DOCTYPE html>
<html lang="en">
<head>
<title>setAttribute Example</title>
</head>
<body>
<img id="myImage" src="placeholder.png" alt="Placeholder Image">

<script>
// Change the source of the image using setAttribute
const img = document.getElementById('myImage');
img.setAttribute('src', 'newImage.png');
img.setAttribute('alt', 'New Image');
</script>
</body>
</html>

2.removeAttribute
<!DOCTYPE html>
<html lang="en">
<head>
<title>Remove ID</title>
</head>
<body>
<div id="uniqueDiv">This is a unique div.</div>

<button onclick="removeDivID()">Remove ID</button>

<script>
function removeDivID() {
const div = document.getElementById('uniqueDiv');
div.removeAttribute('id');
}
</script>
</body>
</html>

46 How to add or remove style of HTML elements in the DOM using JS?
1.stye.setProperty
<!DOCTYPE html>
<html>
<head>
<title>Change Style Example</title>
</head>
<body>
<p id="text">This is a paragraph.</p>
<button onclick="changeStyle()">Change Style</button>

<script>
function changeStyle() {
var paragraph = document.getElementById('text');
// Set a new CSS property
paragraph.style.setProperty('color', 'blue');
paragraph.style.setProperty('font-size', '20px');
}
</script>
</body>
</html>

2.classList.add() **NOt understood properly


47 How to create new elements in DOM using JS?
1. createElement

var newDiv=document.createElement('div');
newDiv.textContent="Newly created div';
document.body.appendChild(newDiv);

output

<div>Newly created div </div>

*****Exmaple
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Demo</title>
</head>
<body>
<p id="demo">A Paragraph</p>
<button onclick="clicking()">clickMe</button>
</body>
<script>
function clicking() {
const newly=document.createElement("div");
newly.textContent="i am new node";
document.body.appendChild(newly);
}
</script>
</html>

2. cloneNode()
<div id="parentElement>
<h1>Existing Element </h1>
</div>
var existingElement=document.getElementById('parentElement');
var clonedElement =existingElement.cloneNode(true);
clonedElement.textContent="clonedElement");
document.body.appendChild(clonedElement);

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Demo</title>
</head>
<body>
<p id="demo">A Paragraph</p>
<button onclick="clicking()">clickMe</button>
</body>
<script>
function clicking() {
const res=document.getElementById("demo");
const cloned=res.cloneNode(true);
cloned.textContent="newly added cloned";
document.body.appendChild(cloned);
}
</script>
</html>

<div id="parentElement">Cloned element</div>

creteElement vs createTextNode()
createElement create new element

createTextNode create element for existing node


<div id="parentElement>
<h1>Existing Element </h1>
</div>

var parentElement=document.getElementById("parentElement");

var newText=document.createTextNode("This is some text");

parentElement.appendChild(newText);

**Remove Child
<!DOCTYPE html>
<html>
<head>
<title>Remove Child Example</title>
</head>
<body>
<div id="parentDiv">
<p id="childParagraph">This is a paragraph that will be removed.</p>
</div>
<button onclick="removeParagraph()">Remove Paragraph</button>
<script>
function removeParagraph() {
// Get the parent element
var parentDiv = document.getElementById('parentDiv');

// Get the child element (the paragraph)


var childParagraph = document.getElementById('childParagraph');

// Remove the child element from the parent


parentDiv.removeChild(childParagraph);
}
</script>
</body>
</html>

**************Error Handling****************
48 Error Handling in JS
Process of managing errors

what is role of finally block


Finally block is used to execute code irrepective of error

what is the purpose of throw statement


Throw statement stops the executionof current function and passes the error to
chatch block of calling function

49 what is Error Propagation in JS?


It referes to the process of passing or propagating an error from one part of the
code to another part using throw statement

50 Error Handling Best Practices


1.use Try catch
2. use Descriptive error Messages
mean error message should be clear
3.Avoid Swallowing( Never leave catch block empty)
4. log errors properly

51 what are the different types of error in JS?


1.Syntax error
2.Reference Error exmaple consol.log(result) result is not defined
3.Type error
number =42
number.toUpperCase()

4.Range Error
const array=[1,2,3]
console.log(array[10]);

****************Objects***********
52 what are objects in JS?
Object is a data type that allows you to store key-value pairs

**ways to create object


Object literal
var person={
name:"happy",
age:20
}

**Object Constructor
var person=new Object();
person.name="happy"
person.age=30
}

***Object.create()

var person={
name:"",
age:0,
role:""
};
var men=Object.create(person);
men.name="Happy";
men.age=30;

********using contructor function


// 3. Using a Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
}

const obj3 = new Person("thirdObj", 25);

53 what is the difference between an array and an object?


Array Object
1.Arrays are collections of values Objects are collections of key-value
pair
2. Arrays are denoted by square brakets[] Objects are denoted by curly braces{}
3. Elements in array are ordered Properties in objects are unordered

54 How to manipulate Objects in JS?


add,modify,delete properties
var person={}

add
person.name="Happy"
person.age=30

modify
person.age=35;

delete
delete person.age
55 Dot Notation vs Bracket Notation
both used to acces property or methods

dot is more popular

but in somecases bracket notaion is the only option

56 How to iterate through Objects in JS?


3 ways
**for..in loop

for(let prop in person){


console.log(prop+ " :" +person[prop]);
}
**Object.keys()
Object.keys(person).forEach((prop)=>{
console.log(prop+ " :"+person[prop]);
}}

**Object.values
Object.values(person).forEach((prop)=>{
console.log(prop+ " :"+person[prop]);
}}

57 How to check if a property exists or not?


var person=new Object();
person.name="happy"
person.age=30
}

**console.log("name" in person) //true

**console.log(person.hasOwnProperty("name")) true

58 How to clone an object?


var person=new Object();
person.name="happy"
person.age=30
}

1. spread (shallow copy)


const cloneObject={...person}

2. Object.assign() (shallow copy)

Object.assing(target,source)

const clonedObject=Object.assign({},person);

**JSON.parse(deep copy)

const clonedOBJ=JSON.parse(JSON.stringify(person));

**Deep vs shllow copy

59 Sets in JS
set objec is a collection of unique values
const uniqueNumber=new Set();
uniqueNumber.add(5);
uniqueNumber.add(10);
uniqueNumber.add(15);

console.log(uniqueNumber)

console.log(uniqueNumber.size);

console.log(uniqueNumber.has(10));

uniqueNumber.delete(10)

it can be used to removed dublicate from set

let myArr=[1,4,3,4];
let myset=new Set(myArr);

let uniqueArray=[...myset];

console.log(uniqueArray);

60 Map Object in JS
collection of key-value paris
const person=new Map();
person.set("name","Alice");
person.set("age",30);

**** Map vs Object


Map Object
1.keys in Map can be of any type keys in regular JS object are
lilmited to strings and symbols
including string,numbers,objects,functions etc

2. A map maintains theh order by key-value as they no guarenteed for order


3.useful when keys are of different types Useful when keys are strings
or symbols and there are simple set of properties

wer inserted

Start of Advance Section


*************Events*******************

61 Events in JS
Event handling is the process of responding to user action in a web page

addEventListener method of JS allows to attach an event name and with the function
you want to perfomn on that event

ex

<button id="myButton">Click me</button>

const button=document.getElementById("myButton");
button.addEventListener('click',function(){
alert('button clicked!');
});
Types of events
1. click
2. mouseover
3.keydown
4.keyup
5.submit
6.focus
7.blur
8.change
9.load
10.resize

// do practicle
62 Event Delegation in JS
It is a technique where you attach a single event handler to a parent to hangle
events on its child elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Delegation with Dynamic Items</title>
<style>
.item {
padding: 10px;
margin: 5px;
background-color: lightgray;
cursor: pointer;
}
</style>
</head>
<body>
<ul id="itemList">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
<button id="addItem">Add Item</button>
<script>
const itemList = document.getElementById('itemList');
const addItemButton = document.getElementById('addItem');

// Event delegation for handling clicks on list items


itemList.addEventListener('click', function(event) {
if (event.target && event.target.matches('.item')) {
alert('Clicked on: ' + event.target.textContent);
}
});

// Adding a new item dynamically


addItemButton.addEventListener('click', function() {
const newItem = document.createElement('li');
newItem.className = 'item';
newItem.textContent = 'New Item ' + (itemList.children.length + 1);
itemList.appendChild(newItem);
});
</script>
</body>
</html>

//do the practilce

63 Event Bubbling and Event Capturing in JS


event Bubbling:- where an event triggered on child element propagets up the DOM
tree,triggering event handlers on its parent elements.

event Capturing:- it is a reverse of event bubbling


What are JavaScript modules, and how do they differ from the older method of using
script tags to include JavaScript files? Can you provide an example of how to use
ES6 modules for importing and exporting functions or variables?
What is the this keyword in JavaScript, and how does its value change depending on
the context in which it is used? Can you provide examples of different scenarios
where this behaves differently?

how to stop event propragation or eveent bubbling


event.stopPropagation()
64 event.preventDefault() method in JS
65 The use of "this" keyword in the context of event handling in JS
66 How to remove (unattach) an event handler from an element in JS

67 what are selectors in JS


like getElementById
querySelector

68 what is closures
lexical scope
A closure in Js is a combination of a function and the lexical environment

function outerFunction(){
const outerVariable ="outer scope";

function innerFunction(){
console.log(outerVariable);
}
return innterFunction;
}

const closure=outerFunction();
closure();
*********Benifits of closure****
example

function createCounter(){
let count=0;
return function(){
count++;
console.log(count);
};
}

const closure=createCounter();

closure(); // output 1
closure(); // output 2

1. closure can be used for data modification with data privacy(encapsulation)


2. persitent data and state-Each time createCounter is called, it creaes a new
closure with its own separate count variable
3. code Reusability- The clousre returned by createCounter() is a reusable counter
function

68 Technique for achieving asynchronous operations


1. setTimeout
2 setInterval
3 callBacks
4 promises
5 Async/await
6 Generator with yeild

69. what is setTimout? how it used for asynchronous operations ?


setTimout() is a build in jS function that allowsy you to schedule the execution of
function after a specific delay ansychnornous.

console.log("start");

setTimeout(function(){
console.log("I am not stopping anything");

},3000);
console.log("not blocked);

output
//start
//not blocked
// I am not stopping anything

70 setInterval ?
setInterval() is a build in JS function that allows you to repeatedly execute a
function at a
specific interval asynchronously
console.log("start");

setInterval(function(){
console.log("I am not stopping anything");

},3000);

console.log("not blocked);
output
//start
//not blocked
// I am not stopping anything
// I am not stopping anything

71. what are promises ?

Important points
1. Promises in Js are a way to handle asynchronouse operations
2. A promise can be in one of three state: pending,resolved or rejected
3. A promise represents a value that may not be available yet but will be availabe
at some point in the future.
const promise=new Promise((resolve,reject)=>{

});
72. when to use Promises
Promises are useful when you need to perform time taking operations in synchronous
manner and later handle the results when the result is available
1. Api calls
2. File Handling
3 Data Fectching
4. Event handling

73. Promise.all();
// check on google
74. Promise.race();
// check on google

75 Differnce promise.all vs promise.race();


// check
76. what is purpose of async/await? compare it with Promises?
const usersUrl = 'https://jsonplaceholder.typicode.com/users';
const postsUrl = 'https://jsonplaceholder.typicode.com/posts';
async function fetchData() {
try {
// Await both promises to resolve
const usersResponse = await fetch(usersUrl);
const postsResponse = await fetch(postsUrl);

const users = await usersResponse.json();


const posts = await postsResponse.json();

console.log('Users:', users);
console.log('Posts:', posts);
} catch (error) {
console.error('Error fetching data:', error);
}
}

fetchData();
Similarities and Differences

1. Promises and async/await can achieve the same goal of handling async operations.
2. aync/await provides a more concise and readable syntax that resembles
synchronous code whereas Promises
uses a chaining syntax with then() and catch() which is not that readabile
3. async/await still relies on Promises for handling the aynch nature of the code

77. what are Browsers APIs in JS ?


API provided by browsers
1. DOM api
2.XHR
3. Fetch API
4. Storage API
aloat more

78 what is web Storeage and its use? how many types


Web store is used to store data locally

Types
1. Local
2. Session Storage

79 Local Storage. how to store,retirve and remove data from it


LocalStorage is a webStoreage feature provided by web browers that allowsy web
applications to store
key-value pairs of data locally on the users' device.

// Storing data in localStorage


localStorage.setItem('key',"value');

const value=localStorage.getItem("key");

localStorage.removeItem("key");
localStorage.clear();

uses

1. Storing user pereference like language perference.


2. Caching data to improve performance
3. Implementing Offline Functionality
4. Storing Client-Side Tokens

80. LocalStorage vs SessionStorage

LocalStorage Session Storage

1.Data Stored in localStorage is accesible Data stored in SessionStorage is


specific to a particular browsing session
across mutiple windows,tabs.
2. pereist data even when browser is closed Data will be cleared if you close
browser
and reopend
3. No expiration datae unless expclicity Lasts for the duration of the
browsing session
removed

81. what are cookies?

Cookies are small piece data that are stored in the users' web browser

document.cookie="cookiename1=cookieValue1";

const cookieValue=getCookie("cookieName");

82. cookie vs WebStorage

1. cookie has a small storage capacity upto 4KB Local/session has upto
5-10MB
2. Cookies are automaticaly sent with every request Data Stored in
webStorage is not automatically send with each request
3. cookie can have an expiration date set Data stored in
webStorage is not associated with an expiration date
4. Cookies are accesble on both client and server side Web Storage is
accessible and mofifiable only on the client side
allows server-side code to read and modify cookie value

83. what are classes


classes server a blurprints for creating objects and defint their structure and
behaviour

Advantave
1.Object creation
2. encapuslation
3. inheritance
4. Code Resuablitiy
5. Polymorphism
6. Abstraction

84 what is a Constructor ?
85. Constructor Function ?
86 use of this keyword
87 ES6 ? new Feature
1. let and const
2. Arrow Functions
3. Template Literals
4. Destructuring Assignment
5. Default Parameters
6. Classes
7. Promises
8. Map and Set Collections
9. Spread and Rest Operators

88.Composition in JS
89 JS Generator functions
90 prototype inJS
91 Temporal dead zone
92 weak hash
93 Does JavaScript support auto type conversion?

Map vs object still confusing

// this keyword
What is the event loop in JavaScript, and how does it handle asynchronous code?
prototypal inheritance
What is the difference between call(), apply(), and bind() methods in JavaScript?
Can you provide examples for each?
arrow vs normal function
Execution context

******this****** in node js
1. consol.log(this) {}
2. inside function

function showThis(){
console.log(this)
}

output global object

3. inside object->function
let obj={
name:"sahil",
f:function(){
console.log(this)
}
}
obj.f()
**return object
output
{ name: 'sahil', f: [Function: f] }

4. inside object in nested function


let obj={
name:"sahil",
f:function(){
function g(){
console.log(this)
}
g();
}
}
obj.f()

return global object

what is curring ?
microtask queue?

Promose.all
let p1=new Promise((resolve,reject)=>{
resolve("resolved 1")
})
let p2=new Promise((resolve,reject)=>{
resolve("resolve 2 ")
})
let p3=new Promise((resolve,reject)=>{
reject("rejected 3")
})

const result=Promise.all([p1,p2,p3]);
result.then((res)=>console.log(res))
.catch((err)=>console.log(err));

if one reject then it will show only rejected one if all resolve then will show all
of them

vs promise.all()
let p1=new Promise((resolve,reject)=>{
resolve("resolved 1")
})
let p2=new Promise((resolve,reject)=>{
resolve("resolve 2 ")
})
let p3=new Promise((resolve,reject)=>{
reject("reject 3")
})

const result=Promise.race([p1,p2,p3]);
result.then((res)=>console.log(res))
.catch((err)=>console.log(err));
it will print which one resolve first and if first one is reject then output is
reject only

so it will return if which one resolve first or reject will not check others

Promise.allSettled

let p1=new Promise((resolve,reject)=>{


resolve("reject 1")
})
let p2=new Promise((resolve,reject)=>{
resolve("resolve 2 ")
})
let p3=new Promise((resolve,reject)=>{
reject("reject 3")
})

const result=Promise.allSettled([p1,p2,p3]);
result.then((res)=>console.log(res))
.catch((err)=>console.log(err));

it will print all with status whether reject or resolved

You might also like