Java Script
Java Script
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
example
let globalVaribale="global" //global
greet();
function greet(){
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
example
//function hoisting
myfunction();
function myfunction(){
console.log("Hello");
}
//variable hoisting
x=10;
console.log(x);
var x;
6 What is JSON?
function example(){
if(true){
var count=10;
console.log(count);
}
console.log(count); // it will access it
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)
let x;
console.log(x) undefined
let y=null;
console.log(y) null
Types
primitive can hold sing value non primitive can hold multiple values
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"
}
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
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
let a=5;
let b=-a;
++a;
Binary
let x=10;
let y=3
x+y; two operands
Ternary
let result =condition?'YES':'NO';
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
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 ?
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);
const number=[1,2,3,4,5];
sum(...numbers);
function(a,b,c,d,e){
console.log(a+b+c+d+e);
}
****REST
************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
**filter()
let d=array.filter((num)=>num%2==0);
output =[2,4];
**slice()
const array=["a","b","c","d","e"];
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
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
let array=[1,2,3,4]
array.sort();
conole.log(array);
array.reverse();
console.log(array);
const fruits=['apple','banna','orange'];
const [first,second,third]=fruits;
example of String
const str="HEllo"
it works somewhat like array but it is String but not exactly an array
console.log(arr);
// Output: ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d", "!"]
spread
*******Loops******
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
for-in loop
const person={
name:"happy"
}
const person={
name:"happy"
}
Object.values(person).forEach(value=>{
});
for of loop
if(item==2){
break;
}
}
array.forEach(function(item){
console.log(item);
if(item==2){
break; //error
}
});
**********************Functions********************
Types
Named function
Anonymous Function
Funciton Expression
Arrow Function
IIFE
Callback Function
Higher order Function
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);
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
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]);
addEventListener method of JS allows to attach an event name and with the function
you want to perfomn on that event
ex
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
const double=curriedMutiply(2);
console.log(double(5));
************Strings************
34 what is a string?
var str="String"
it is a data type used to store and manipulate data
var myname="Happy"
var str3=`hello ${myname}`;
console.log(str3);
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();
replace
result.replace('world","JAvaScript");
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
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>
<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>
var newDiv=document.createElement('div');
newDiv.textContent="Newly created div';
document.body.appendChild(newDiv);
output
*****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>
creteElement vs createTextNode()
createElement create new element
var parentElement=document.getElementById("parentElement");
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');
**************Error Handling****************
48 Error Handling in JS
Process of managing errors
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
**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;
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
**Object.values
Object.values(person).forEach((prop)=>{
console.log(prop+ " :"+person[prop]);
}}
**console.log(person.hasOwnProperty("name")) true
Object.assing(target,source)
const clonedObject=Object.assign({},person);
**JSON.parse(deep copy)
const clonedOBJ=JSON.parse(JSON.stringify(person));
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)
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);
wer inserted
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
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');
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
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
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
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
Types
1. Local
2. Session Storage
const value=localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();
uses
Cookies are small piece data that are stored in the users' web browser
document.cookie="cookiename1=cookieValue1";
const cookieValue=getCookie("cookieName");
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
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?
// 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)
}
3. inside object->function
let obj={
name:"sahil",
f:function(){
console.log(this)
}
}
obj.f()
**return object
output
{ name: 'sahil', f: [Function: f] }
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
const result=Promise.allSettled([p1,p2,p3]);
result.then((res)=>console.log(res))
.catch((err)=>console.log(err));