[Go to site: main page, start]

0% found this document useful (0 votes)
3 views85 pages

Learning JavaScript

This document provides a comprehensive overview of JavaScript, covering its syntax, data types, operations, and best practices. It explains variable declaration, type coercion, and the differences between primitive and non-primitive data types, along with various methods for strings, numbers, arrays, and objects. Additionally, it introduces API concepts, including REST and SOAP, and emphasizes the importance of writing clean, readable code.

Uploaded by

Hitesh Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views85 pages

Learning JavaScript

This document provides a comprehensive overview of JavaScript, covering its syntax, data types, operations, and best practices. It explains variable declaration, type coercion, and the differences between primitive and non-primitive data types, along with various methods for strings, numbers, arrays, and objects. Additionally, it introduces API concepts, including REST and SOAP, and emphasizes the importance of writing clean, readable code.

Uploaded by

Hitesh Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Learning JavaScript

JavaScript is a scripting language. It runs on a browser by linking it to


a html file. We can also run JavaScript without browsers using
Nodejs.
[Link]() – used to print anything to console.
[Link]([]) – used to print multiple variables at once.
*Variable is a container to store any value. It can be declared and
assigned value in multiple ways.
const varName = value; - used to initialize a variable, whose value we
don’t want to be changed in future.
let varName;
var varName;
**use of var is discouraged due to issue in block scope.
**can initialize a variable without use of any of these three
keywords, but it is not recommended.
*if you only declare a variable and not assign any value to it, its
datatype and value is “undefined”.
let and const are hoisted but not initialized.
Accessing them before declaration throws ReferenceError.
Example:
[Link](a); // ❌ ReferenceError
let a = 10;
This prevents bugs that var allows.
Prefer:
const by default
let only when reassignment is needed
Avoid var entirely in modern codebases.
“use strict” – treat all js code written in this file as newer version.
**javascript is a forgiving language but it does not mean you should
take advantage of that. Write proper and readable code.
Datatypes in javascript:
let name = “Hitesh” // string
let name2 = ‘sattu’ // string
*use bigInt for the values which are not in range of the datatype
number.
let age = 20 // number
let isAdult = true // Boolean
null – standalone value/datatype
undefined – datatype of a variable which have no value assigned.
Object
[Link](typeof undefined) // undefined
[Link](typeof null) // object

Conversion Operations
Number() – converts to number datatype
**this will try to convert any given variable to a number datatype
even if it should not be possible. If the value is not compatible to be a
number, it will be converted to NaN – Not a Number.
**if the passed variable has a value null, it will be converted to 0. If it
is undefined, it will be converted to NaN.
**if it has a Boolean value, it will be converted to its number
counterpart. i.e 0,1.
Boolean()
1->true, 0->false
“….”->true; “” -> false
String()
Type Coercion
JS automatically converts types in many operations:
Example:
"5" + 2 = "52"
"5" - 2 = 3
true + 1 = 2
null + 1 = 1
undefined + 1 = NaN
Rule of thumb:
+ prefers string concatenation
Other operators prefer number conversion

Operations
Arithmatic
Assignment
Increment/decrement
Comparison

**make sure to compare variables of same datatype or you will get


unpredictable output.
**Comparison converts null to a number(0) but == does not convert
it to a number.
*comparison and equality check are two different things
=== -> checks for both datatype and value.
Equality Operators
===
→ No conversion
→ Always safe
==
→ Performs coercion
→ Dangerous in production
Industry rule: Always use === unless you explicitly want coercion.

More about Datatype


//categorization based on how they are stored in memory
Primitive and non primitive
Primitive: 7 types
String, Number, Boolean, Null, Undefined, Symbol, BigInt
const id = Symbol(‘123’);
const aid = Symbol(‘123’)
*even if you assign same value in symbol, it will make it different
when outputting.
// Reference/nonprimitive
Array, Objects, Functions
**javascript is static or dynamically typed? -> dynamically typed
language.
Const heros =[1,2,3]; // array
Let obj ={name:”Hitesh”, age:20} //object
**can access the values in object using ‘.’
Function(){}
**you can also assign a function to a variable
const myFunc = function(){[Link](heros)}
[Link](typeof myFunc) // will return function but it is called
object function.
Datatype of all reference datatypes is object except function.

Memory
Stack Memory (primitive datatype), Heap Memory(reference
datatype)
Stack memory returns a copy of variable, heap returns address of the
variable.
Primitive stored in stack frame
Reference value stored in stack → points to heap object

Day 2: 18 january, 2026


String
**can be denoted using single quote or double quote.
Const name = ”hitesh”
**can be concatenated using + operator.
**In modern javascript you should use back-tiks to combine two or
more strings or a string with some other datatype -> ``. it does string
interpolation.
const name = “hitesh”;
Const repoCount = 30;
[Link](`Hello I’m ${name} and repo count is ${repoCount}`)
Const gameName = new String(“Hitesh”); //creates string object with
its methods.
**master important string methods.
*can access any character of string using index.
.length
.toUpperCase
**does not change orignal value of string.
.charAt() //can find char at given index
**”name”[1] can also find the char at given index. When using this
bracket notation, you cannot assign or delete a value.
.indexOf(‘’) // find index of given char
.substring(startIndex, endIndex)
.slice(start, end)// same as substring but can enter -ve values.
.trim() // removes starting and end spaces.
.replace(whatToReplace, replaceWithWhat) //replaces part of string
with given string.
.includes()// to check if string contains given value
.split()//splits string based on separator and return array.

**when you compare two strings, they are compared case-sensitively


*javascript distinguishes between String objects(new String()) and
string literals.
*String object can be converted to its counterpart literal
using .valueOf() method.

Numbers
let score = 50;
let balance = new Number(100);

.toString()//returns the number as string.


.toFixed(num)// precesion value after decimal point
.toPrecision()//returns the precise value of whole number and it also
rounds it off.
.toLocalString() // add commas to a huge value
**can pass ‘en-IN’ as argument to add commas according to Indian
standard. Default in US standard.
Maths
*library. It has many math functions.
[Link](-4) // returns the absolute value. I.e. positive value
[Link](4.3)//rounds off to closest whole number
[Link]()// round off to higher number
[Link]()// rounds off to lower number
[Link]()
[Link]()// return maximum value
[Link]()//gives random values between 0 and 1.
**can multiply returned value with any number for custom limit. Add
1 to returned value to insure it is not 0.
*you can also make it to return whole number by wrapping it with
[Link]().
*can define custom limit like this
const minVal = 10;
const maxVal = 20;
//now if we want to get random values between 10 and 20 we can do
this:
[Link]([Link]([Link]()*(maxVal - minVal + 1))
+minVal);
**how this works is that it will multiply the random value with 20-
10+1, which is 11. (+1 insures that it does not return the lower limit).
This will return the values between 0 and 10. now we add minVal to
it i.e. 10, it will make sure that random value is between 10 and 20.
At last the [Link] method will make sure it does not return float
values.
Date
Let myDate = new Date()
.toString()
toDateString()// returns day month, date year
.toLocalString()// returns date/month/year, time
**typeof myDate = object
*can initialize exact date
Let myCDate = new Date(2026, 0, 17)
[Link]([Link]())// return mon jan 23 2026
Let myDate2 = new Date(“01-14-2026”)
//also have timestamps
Let myTimeStamp = [Link]()
.getTime()//return time in miliseconds from the first date(1 jan 1970)
till now
*can be converted to seconds using standard multiplication of
standard; can remove decimal values using [Link]
**Date has many methods like getDay or getMonth
//can customize the format of .toLocalString()
[Link](‘default’. {
Weekday:”long”
})
**can define many properties
Arrays
Collection of multiple items under same variables. Are resizable.
Index starts from 0.
[Link] creates a shallow copy
*shallow copy is a copy whose properties share the same reference
point as source
*deep copy is a copy whose properties does not share same
reference point as source
Const myArr = [1,3,5,6]
const hero = [“hello”,”me”]
Const myArr2 = new Array(1,2,3,4)
.length property is used to find length of array

//array methods
.push() // adds value to array
.pop() // removes end value and returns it
.unshift() // adds value to start of array // not recommended because
of optimization issues
.shift() // removes the first value of array
.includes() // checks if array includes some value, returns boolean
value
.indexOf() // returns the index of given value. If the value is not
present it returns -1.
.join() //combines array and converts the value to string
.slice(start, end)// return the specified section of array. Does not
include the end index. Does not change the original array
.splice(start, number)// starts from start index and deletes the
number of values from that index and returns the removed values.
Changes the original array
**if we push an array into another array, it does not joins them but it
creates a nested array .I.e. array inside an array.
.push() can take any argument and it modifies the original array.
.concat() //combines the two array and returns a new array.
***spread operator:
Spreads the array into individual elements.
Const allHeros = […marvelHero, …dcHero]
*this performs the array concatenation
*spread operator(…arrayName) if very useful and is used in many
situations.
.flat(depth)//returns the array with all the subarray elements as its
own elements.
**can write Infinity as depth but not recommended. Can do in
testing.
**can access many other array methods with [Link].
[Link]() //checks If the given argument is an array
[Link]() //makes an array from the given argument
*can pass object in it
**[Link]({name:”hitesh”}) returns an empty array. You have to
specify from what to make the array(keys or values).
[Link]() // returns a new array from set of elements
//important array methods
.map((x)=>x*2)
*.map is an iterative method. It returns an array after performing a
given action on all the elements. (this does not change the orignal
array). use this method if you want to use its return value, otherwise
use foreach loop.
*syntax - [Link](callbackfn) or [Link](callbackfn,
thisArg)
*callbackfn is the function to be executed. thisArg is the value to be
used as this.

Objects
Objects can be declared in two ways : as a literal, as a constructor
//as constructor - singleton object
[Link]
//object literals
Let mySym = Symbol(“key1”)
Const jsUser ={
Name:”hitesh”,
[mySym]:”myKey1”,
Age:20,
“location”:”sardulgarh”,
isLoggedIn:false
}
**can access using [Link]
**also using obj[“key”]
**cannot access the location property using ., it can only be accessed
using jsUser[“location”]
**to use symbol datatype as key, you have to write it in [] and to
access it you also have to use the [] format.
[Link](jsUser) // freezes the object. The changes made after
freezing are not propagated. It does not give error, it just does not
apply the changes.
*can assign function as the value of a key in object.
[Link] = function(){[Link](“hello world”)}
*now if you do [Link]([Link]), it prints [Function
(anonymous)], it’s the reference of that function. You have to do
[Link]([Link]())
[Link] = function(){[Link](“hello ${[Link]}”)} //
‘this’ keyword is used to tell the code that the property we are asking
is from the current object.

Singleton Object
Const tinderUser = new Object();
[Link] = “123”
[Link] = “Hitesh”
[Link] = false
[Link](tinderUser)

Const rUser ={
Email:”hitesh@[Link]”,
Fullname:{
Userfullname:{
Firstname:”hitesh”,
Lastname:”kumar”
}
}
}

[Link]([Link])

Merging objects
Const obj ={1 :“a”, 2:”b”}
Const obj2={3:”a”, 4:”b”}
Const obj3={obj, obj2} //this will merge them but will make nested
objects.

//proper way
const obj4 = [Link]({},obj, obj2)
** can also do this - const obj4 = [Link](obj, obj2) but above
method is recommended.
*in the arguments of [Link](target, source).
**there can be multiple sources but only one target. The first
argument is a target and all the next are sources. that’s why in
recommended method target is an empty object.

// you can also use spread opoerator


Const obj5= {..obj, …obj2}

**you can also store objects in array


//when values come from database
Const users = [
{name:”hitesh”,age:20},
{name:”kishan”,age:19},
{name:”lakhan”,age:20},
]
[Link](users[0].name)

//getting all the keys of an object


[Link](tinderUser)
//getting all the values of an object
[Link](tinderUser)
**both of the above methods return an array
[Link](tinderUser)//returns all the key value pair as arrays in
an array
*[[],[],[]]
object_name.hasOwnProperties(‘property_name’)//checks if an
object has a particular value. returns boolean value

Object destructuring and json API

Const course ={
Coursename:”javascript”,
Price:”999”,
courseInstructor:”hitesh”
}
Const {courseInstructor} = course;
*this will make courseInstructor available without having to write
[Link] every time.
*you can access that property just by writing the property name.
You can also give some other name to that property which you will
use.
Const {coursename: name} = course
*this will get the property coursename from the object course and
assign “name” as its name.
Destructuring syntax is a javascript syntax which makes it possible to
unpack properties from objects, elements from array, into distinct
variables. We can use these variables however we want

API
Application programming interface enables applications and
softwares to communicate and share data easily.
It is like waiter. It takes request from user, requests from the server
and gets the response from the server and returns the response to
the user.
How do APIs work
1. Request -> the client sends request to the API endpoint.
2. Processing -> the API forwards the client request to the server.
3. Response -> the server processes the request and gives the data
to API
4. Delivery -> the API then delivers the data to client.
Types of API architecture
API architecture
It defines how the data is shared between systems and softwares.
REST API(Representation state transfer)
1. REST is a simple, flexible architecture. It uses HTTP methods (GET,
POST, PUT, DELETE) to communicate.
2. Data format:JSON, XML
SOAP(SIMPLE OBJECT ACCESS PROTOCOL)
1. SOAP is a more rigid protocol which requires XML based messaging
for communication. It shares structured data in XML
2. DATA format:XML
graphQL
1. Modern query language which lets clients fetch only the data they
need.
2. Data format:JSON
gRPC
1. High performance framework using protocol buffers(protobuf)
2. Data format:binary

Most commonly used data format is JSON


{
“name”:”hitesh”,
“coursename”:”javascript”,
“price”:”free”
}
*this is the format of JSON.
**keys should be strings .
Sometimes the response from the APIs is in array form instead of
object. It returns an array of object.
[
{},
{},
{}
]

Function and parameters


//syntax
Function function_name(num1, num2){
//code to execute
}
Function_name();//this calls the function and executes the code
inside it
**num1 and num2 are the parameters.
We can pass some variables or arguments in the function call if we
have parameters in function definition.
Function_name(price, quantity);
*here the price would be passed into num1 and quantity would be
passed into num2.
**we can add return keyword in the function so that it returns some
value.
*if we call a function as an assignment to a variable, the value which
the function returns is stored in that variable. If there is no return
statement it will store undefined.
Function sum(a,b){
return a+b;
}
Let result = sum(5,6)// the function will return 5+6, which is 11 and
store it into the result variable.
*we can also add some default values to the parameters.
Function sum(a,b=5 ){….}
Now you can call the function with only one argument and it will
work. When we pass arguments they are assigned to the parameters
from left to right. So if one argument I passed, it will get assigned to
parameter a and b will take default value of 5.
You can pass multiple value as parameters by using rest operator.
Function calculate(…num1){
return num1//it will return an array of these numbers.
}
//passing an object as the parameter
Function handleObject(anyObject){
[Link](`Username is ${[Link]} and price is $
{[Link]}`)
}
**you can also directly pass an object In function call
handleObject({username:”hitesh”, price:6999})

**can also pass an array as parameter

Global Scope and local scope


Let a = 0;
Const b = 10;
Var c = 20;

{} - this is a scope
*var does not follow block scope.
* if you declare any variable using var keyword, it will be available
outside of its scope.
*if you declare anything inside the global scope, it is available inside
all other block scopes but any value declared inside a block should
not be available inside global scope or other block scopes other than
itself.

Scoping level and mini hoisting.


*inner block can access the variables from outer block but outer
block cannot access the values declared in inner block
//hoisting
**if you call a function and declare it after, it will not throw any error.
**but if you declare a function as a variable, you cannot call it before
its declaration.

This and arrow function


//There is also a modern version of function which is Arrow function.
//syntax
Const greet = (name)=>{//name is a parameter
Return `Hello ${name}`
};
[Link](greet(“hitesh”));
**many things in modern web development are done using arrow
function. It is used for assigning a function to a variable and that
variable can be passed as an argument to another function.
//’this’ keyword is used to refer to current [Link] in objects
*when you [Link](this) in a function, it will print something but
if you do it inside an arrow function it will print empty object{}
Const greet2 =(name) => `Hello ${name}`
[Link](greet2(“hitesh”));
//this will do the same thing as the greet function. This is called
implicit return.
*when returning object using Implicit return wrap it in paranthesis.

IIFE - immediately invoked function expressions


//execute the function immediately and prevent the polution from
the global scope
// for writing an IIFE, wrap the function definition in parenthesis and
add parenthesis block(function call) at the end.
(function chai(){
[Link](“database connected”);
})();
*you should add semi colon after the end of IIFE or sometimes it will
throw errors when writing IFFE after another IIFE
*can also write arrow functions as IIFE.

How does javascript work ?


Javascript execution context
//global execution context is always created. And this keyword can
also refer to this.
//js is single threaded
--global execution context
--function execution context
--eval execution context

//suppose this is the code


Let val1 = 10
Let val2 = 5
Function addNum(num1, num2){
Let total = num1 + num2
Return total
}
Let result1 = addNum(val1, val2)
Let result2 = addNum(10,2)

1. Global execution Phase


 Global context is created
2. Memory creation Phase // allocates memory to variables.
 Space is allocated
 Variables are assigned values - undefined
 Functions gets their definition stored in them
 Val1 -> undefined
 Val2 -> undefined
 addNum -> definition
 Result1 -> undefined
 Result2 -> undefined
3. Execution Phase
 Values are assigned to variables
 Val1 <- 10
 Val2 <- 5
 addNum-> new execution context(
New variable
Environment + execution thread
Memory phase :
Val1 -> undefined
Val2 - undefined
Total -> undefined
Execution phase:
Num1 <- 10
Num2 <-5
Total <-15
Total gets returned to global execution and this execution
context gets deleted
)
 Result <- 15
 addNum -> new execution context(
 new environment and execution thread
 Memory phase
 Val1 ->undefined
 Val2 - >undefined
 Total ->undefined
 Execution phase:
 Num1 <- 10
 Num2 <-5
 Total <-15
 Total gets returned to global execution context and this
execution context gets deleted
)
 Result2 <-15

Call stack - LIFO


Control flow in javascript
//if
If(condition){
//If condition true code in this block gets executed
}else{
//this code runs when condition in if statement is false
}
Comparisons: <, >, <=, >=, ==, !=, ===, !==
//shorthand notation
If (condition) [Link](“test”)
//if(condition) [Link](“test”), [Link](‘test2”);
*above line can also be run but is not recommended as the code
becomes difficult to read

//can do nesting in conditionals


If(){
//code
if(){
//code
}
}else{
If(){
//code
}
//code
}

//can also check multiple conditions using elseif


If(){
//code
}else if(){
//code
}else{
//code
}

//can also check multiple conditions using one if statement using


AND, OR, NOT operators
If(condition1 && condition2 || condition3){
//code
}
//switch case
//syntax
Switch (key){
Case value:
//code
Break;
Default:
//code
Break;
}
//key is the variable you want to check
//value is the value which is used for comparisons
//adding break; at the end is necessary. If you don’t add it, if one case
gets matched all next cases gets executed except default.
//falsy values
False, 0, -0, BigInt 0n, “”, null, undefined, NaN
//truthy values
Values which are not falsy, “0”, ‘false’, “ ”, [], {}, function(){}
Nullish Coalescing Operator (??) : null undefined
Val1 = 5??10 ///assign 5
Val1 = null??10 //assigned 10
Val1 = undefined??15//assigned 15
**this is used to handle errors

Ternary operator
Condition?if true : if false

Iterators
//for
For(let index = 0; index < 5; index++){
[Link](“hello”);
}
//can also do for loop nesting
//break - stop the whole loop
//continue - skip the rest of the current iteration and go to next one.
//while
While(condition){
//code
}
//code in while loop keeps executing while the condition is true.

//do-while
Do{
//code
}while(condition)
//in do-while loop, code gets executed one time then condition is
checked for all of the next iterations
**work is done first then condition is checked
Higher order array loops
For of loop
//syntax
For (const iterator of object){
//code
}
*the iterator is a variable. The object here refers to anything on
which you want to apply this loop(array, object, string and anything
else). Sometimes people confuse it with the object datatype or
simply objects in javascript.
Const arr = [1,2,3,4,5]
For (const num of arr){
//code
}

//Maps (datatype)
Const map = new Map()
//it is an object that holds key value pairs,
//keys should be unique in Maps.
[Link](‘IN’, ‘INDIA’)
[Link](‘USA’, “United States of America”)
[Link](map)//map(2){“IN” => ‘INDIA’, ‘USA’ => ‘United States of
America’}
For (const key of map){
[Link](key)
}
//this will print each key value pair as an array
//if you want each key and value separately, you need to destructure
them.
For (const [key, value] of map){
[Link](key, ‘:-’, value;
}

const obj ={
name:'hitesh',
age:19,
course:'bca'
}
[Link](obj)

//this does not work


for (const i of obj) {
[Link](i)
}

//for in loop
// this works
for(const i in obj){
[Link](i)
}

For (const key in obj){


[Link](`${key} is ${obj[key]}`)
}
//Obj[key] gets the values of the given key

**when you apply for in loop on arrays, it works on their keys.


**maps are not iteratable using for in loop, but it doesn’t throw
errors.
**mostly used for objects - for in loop
//for each loop
//for arrays
[Link](function (val) {}) //this is callback function and
automatically iterates over each element
// you can also use arrow function as a callback function.
//can also pass previsouly declard functions as callback functions
Function printMe(item){
[Link](item)
}
[Link](printMe)// you don’t have to call the function here, you
only need to pass the reference.
//it automatically calls it and puts each element of array into the
parameters of this function.

//foreach loop doesn’t only get the item, it also gets index and whole
array
[Link]( (item, index, arrr) => {
[Link](item, index, arrr)
})

//foreach loop does not return any values


//.filter
Const nums = [1,2,3,4,5,6,7]
Const newNums = [Link]( (num) => num>4)
//returns the values which pass the condition check
//if you open scope, you need to use the return keyword to return
the values. If you don’t open scope like above example, it impliciltly
returns the values

//.map
Const addNums = [Link]((num)=>num+10)
//performs given operation on each element and returns

//chaining
Const newNum = [Link]((num) =>
num*10).map((num)=>num+1).filter((num) => num>=40)

//.reduce
Const arr = [1,2,3,4,5,6,7,8,9]
Const num = [Link]((acc, currVal)=>acc+currVal,0)
//acc = accumulator, currVal = current value, 0- initial value
//currVal is the current value over which the reduce method is while
iterating the array. Acc does not have a value at start, so we give it
initial value after the callback function.
//in this example first the acc is 0 and currVal is one at start. Then
after the callback function is completed, return value of that callback
function gets stored in acc, and this goes on for all the elements and
the reduce method returns the acc.

const shoppingCart = [
{
itemname:'js course',
price:1000
},
{
itemname:'java course',
price:500
},
{
itemname:'css course',
price:700
},
{
itemname:'python course',
price:900
},
{
itemname:'html course',
price:400
},
]

const totalPrice = [Link]((acc,


currItem)=>acc+[Link],0)
[Link](`total price of the items you
bought is : ${totalPrice}`)

const itemList = (
[Link]((acc,
curval)=>acc+[Link],'')).trim().split
(' course')
[Link](itemList)
DOM Manipulation
*Window object
*Document object model
*html collection, node collection and array are different things.
Can select elements form DOM using selectors
Selection using id
[Link](‘id-name’)
*it returns the whole value.
[Link](‘id-name’).id //returns the id of element
[Link](‘id-name’).className //returns the class
of element
[Link](‘id-name’).class //gives undefined
//another way is : .getAttribute()
[Link](‘id-name’).getAttribute(‘id’) //returns the
id of element
//can get all the attribute of the element using this.

*can overwrite values of attributes using : .setAttribute()


[Link](‘id-name’).setAttribute(‘class’, ‘heading
test’) //sets the class of element as “heading test”.
Can store in variables :
Const title = [Link](‘title’);
*now we don’t have to write getElementById everytime we want
title.
we can use the title variable
[Link] = ‘green’ // can set style of element using
this
**[Link] = “value”
[Link] //to get all text content of a element. Even if
not visible
[Link] //to get only visible text of element.
[Link] // gets all the html inside of the element.

[Link](‘className’)//gets an html
collection of elements of given class name.
[Link]()//gets first occuring element of given
query
“tag” - gets using html tag
“#id” - gets using id
“.class” - gets using classname

Can also get specific elements


[Link](‘input[type=”password”]’)//gets the first
input tag which has type password.
Can target multiple elements using :
.querySelectorAll()//gets all the element of given query
*returns a NodeList
*nodelist and html collection are not pure arrays. These are different
*these has many methods of arrays but not all.
*can use all the array methods by converting them into arrays using
[Link]() method.

Const parent = [Link](‘.parent’)


[Link](parent)// prints the whole element html
[Link] //gets an html collection of all the child elements of
parent element
.firstElementChild//this property gets the first child element of given
parent element
.lastElementChild//gets the last child element of given parent
element

[Link]//We can get parent element from


child element
[Link] //gets the next adjacent
element

[Link] //gets all the child of given parent, not just main
childern but all the childs. Such as first line break and comments.
Returns a NodeList

Creating elements using javascript


createElement(‘elementTag’)// creates an html element of given tag.
Const div =[Link](‘div’)// creates a div element
and stores it into the given varible.
//can add properties
[Link] = “”
[Link] = “”
[Link](‘attribute-name’, “attribute-value”)
Can change style using [Link] = “property”

[Link] = “Hitesh”
//can also do(more optimized approach):
Const addText = [Link](“Hitesh”)
[Link](addText)
//appendChild() method appends a child element in selected
element
*can replace existing element with another using replaceWith()
[Link](addText)//replaces div with addText
**.innerHTML changes the html inside the given element. It does not
change the html of element itself. For that use .outerHTML, it gets
the html of the element itself and inside it.
//remove element:
[Link]()//removes the selected element from the DOM.(here div
).
**can get values froms input tags using .value. It returns string
**can convert that string using parseInt
*serInterval(function(), 1000) //makes an function run continuosuly
after given time
*let date = new Date();
[Link]() //this gets the current time from the date.

Events in Javascript
*can add onClick event directly in html tags. Can add onClick event in
js and assign a function to it.
But above method are not recommended.
You should use .addEventListener(‘event-name’, function(e))//default
3rd parameter is false. It is event bubbling. Write true for event
capturing. In event bubbling, event propagation goes from bottom
element to top. In event capturing, event propagation goes from top
to bottom.
* ‘e’ is event object
*[Link](e) prints all the information of that event object
//attachEvent was used before but not used now
‘click’ : what to do when an element is clicked

Events: type, timestamp, defaultPrevented, target, toElement,


srcElement, currentTarget, clientX, clientY, screenX, screenY, altKey,
ctrlKey, shiftKey, keyCode

*event propagation - if you click an element, its parent element also


get clicked, so use [Link]()
[Link]() // prevents the default behaviour of the element
when clicked.
[Link] - returns the whole element from which the event is coming
*to get parent element use [Link]
*can get html tag of target element using [Link]

*event spillover
Async code
 Javascript
 Synchronous
 Single threaded
 Execution context
 Execute one line of code at a time
 Console log 1
 Console log 2
*each operation waits for the last one to complete before executing.
*call stack, memory heap

 Blocking code
 Blocks the flow of program
 Read file sync
 Non Blocking code
 doesn’t block the execution
 Read file async
*depends on use case
EVENT LOOP
 Js engine
 Memory heap
 Call stack
 Web Api
 Dom api
 Settimeout
 Setinterval
 Fetch
Settimeout and setinterval goes in register call stack and then into
task queue which then adds them to call stack.
Fetch() goes through promises which has high priority queue and it
also adds them to callstack but before task queue
setTimeout(handler, timeout)//handler is a callback function with no
name. Timeout is the amout of time in miliseconds after which to
execute that function. Only runs once
SetInterval(handler, time)//same as settimeout, but runs infinitely
*dont call the function in the handler, just give the reference of that
function.
clearTimeout(reference of settimeout)//stops the timeout function
before its execution
clearInterval(reference of setInterval)//stops the executing the
function in setinterval
*hexcode values of a color - “0123456789ABCDEF”
[Link] gets the key pressed
[Link] gets the ASSCI code of key
[Link] gets the string code of key

Api request and v8 engine


//[Link]
//[Link]

//json formatter
//XMLHttpRequest was used in past. It is very powerful.
Const xhr = new XMLHttpRequest();//creates an object
*[Link](‘method’, ‘url’)// sends a request on given url with the
method specified
[Link](‘GET’,
‘[Link] get request
to this url.
//when request is sent states change
[Link]([Link])//tracks readystate one time
[Link] = function(){
[Link]([Link]);
//it returns a response text
If([Link] ===4){
//[Link](responseText) does not work
[Link]([Link])
[Link]([Link])//this prints null
}
}
*’this’ refers to current context.
*above line continously tracks the state
[Link]();//actually sends the request.
If you do :
Const data = [Link]
[Link]([Link])
This will print undefined. If you print typeof data,, it will print string.
So remember, most of the time response from url comes as string,
sometimes it comes directly as object
So do :
Const data = [Link]([Link])
[Link]([Link])//now this will work
//[Link](typeof data) prints object
*[Link] converts string data to json data or object data

Here is a simple API request program :


<script>
const tableBody =
[Link]('#table-body');
const allowedFields = ['id', 'login',
'name', 'bio', 'location', 'followers'];

function createTableRow(key, value) {


const row =
[Link]('tr');
[Link] = `
<td><strong>$
{key}</strong></td>
<td>${value || 'N/A'}</td>
`;
[Link](row);
}
const xhr = new XMLHttpRequest();
[Link]('GET',
'[Link]
);
[Link] = function () {
if ([Link] === 4 &&
[Link] === 200) {
const data =
[Link]([Link]);
// Clear existing content
[Link] = '';
// Loop through allowed fields
to maintain specific order
[Link](field =>
{
if
([Link](field)) {
createTableRow(field,
data[field]);
}
});
}
};
[Link]();
</script>

Console
Console is a dubuging tool
*node js is implementation of V8 engine
It gives runtime for js
*most of the functions in javascript comes from api
*v8 engine runs javascript
*it is made in c++
*v8 engine provides debuging tool and apis for development

Promises in Javascript
A Promise is an object representing the eventual completion or
failure of an asynchronous operation.
*remember the most important part, it is an ‘object’.
The promise object represents the eventual completion (or failure) of
an asynchronous operation and its resulting value.
Promise is a proxy for a value not necessarily known when the
promise is created. It allows you to associate handlers with an
asynchronous action’s eventual success value or failure reason. This
lets asynchronous methods return values like synchronous methods,
instead of immediately returning the final value, the asynchronous
method returns a promise to supply the value at some point in
future.

the actual data (e.g., API response, database result) is unknown when
the code runs, the promise acts as a proxy, allowing immediate
handling of success or failure once finalized.
Key details:
Proxy/Placeholder: The Promise stands in for a value that hasn't
arrived yet.
Asynchronous: It handles operations that take time, preventing code
from freezing.
States: The promise starts as pending, then
becomes fulfilled (success) or rejected (error).
Chaining: .then() and .catch() handlers are attached to manage the
eventual result, even if it hasn't been computed yet.
Asynchronous programming allows a program to perform multiple
tasks concurrently without waiting for one long-running task to
finish, making applications more responsive and efficient, especially
for I/O-bound operations like network requests or file reading, by
starting a task and moving on to others, handling the result later via
callbacks, promises, or async/await. It contrasts with synchronous
code, where tasks execute sequentially, one after another.
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
A promise is said to be settled if it is either fulfilled or rejected, but
not pending.
.
*most of the promises are consumed by you
For now just for example
//fetch(‘[Link]
hiteshchoudhary’).then().catch().finally()
Making promises
Const promiseOne = new Promise();
//this came in es6
When promises were not available, external libraries were used.
(bluebird)

Const promiseOne = new Promise(function(resolve, reject){


//do async tasks here
//db calls, cryptography, network
setTImeout(function(){
[Link](‘async task is complete’)
//you have to connect resolve and then()
resolve()
}, 2000)
})
*what does reslove, reject do? Why did we write it there?
resolve(value): You call this when the task is successful. It changes
the Promise status from pending to fulfilled. Any data you pass
into resolve() will be received by the .then() block later.
reject(error): You call this when the task fails (e.g., a network error or
a database timeout). It changes the status to rejected. The error you
pass is caught by the .catch() block.
//consuming promise
[Link](calbackfn)
*it automaticaly gets an argument of a value returned by the promise
[Link](function(){
[Link](“promise consumed”)//runs after the async task is
complete
})
//another way
New Promise((resolve,reject)=>{
setTImeout(()=>{
[Link](‘async task 2’)
resolve();
}, 5000)
}).then(function(){
//because we didn’t store promise in any variable, we can directly
apply .then() and other methods
[Link](‘async 2 resolved’)
})

*pass data in resolve, it will be used by then()


*mostly objects
Resolve({username:’hitesh’, id:2337})

const promiseThree = new Promise(function(resolve, reject){


setTimeout(() => {
resolve({username:'Hitesh', email:'hitesh@[Link]',
id:2337})
}, 2000);
})

[Link](function(user){//object is passed by resolve


[Link](user)
})

const promiseFour = new Promise(function(resolve, reject){


setTimeout(() => {
let error = false;//error based checking
if(!error){
resolve({username:'Hitesh', email:'hitesh@[Link]',
id:2337})
}else{
reject("ERROR: something went wrong")//gives error
//this is returned to the .catch()
}
}, 2000);
})
[Link](function(user){//object is passed by resolve
[Link](user)
return [Link];//this return value goes to next then()
}).then((name)=>{//can also do .then() chaining
[Link](name)
}).catch(function(error){
//.catch() is executed when state of promise is rejectd
[Link](error)
}).finally(()=>{
//.finally() is always executed
[Link]("the promise is either resolved or rejected")
})

Async/Await
async and await are JavaScript keywords that simplify working
with Promises by allowing you to write asynchronous code that looks
and behaves like synchronous code.
async Keyword: Prepended to a function to make it asynchronous.
An async function always returns a Promise; if it returns a value,
JavaScript automatically wraps it in a resolved Promise.
await Keyword: Used only inside an async function (or at the top level
of a module). It pauses function execution until the Promise settles
(resolves or rejects).
*does not handle catch properly
const promiseFive = new Promise(function(resolve, reject){
setTimeout(() => {
let error = false;//error based checking
if(!error){
resolve({username:'Hitesh', email:'hitesh@[Link]',
id:2337})
}else{
reject("ERROR: something went wrong")//gives error
//this is returned to the .catch()
}
}, 2000);
})

async function consumePromiseFive(){


//wait till promiseFive is settled and store the return value in a
variable. gets from resolve or reject
const response = await promiseFive;
//promise is an object, that is why it is not consumed like
promiseFive();
[Link](response);
}
//now you have to run this function for the promise to start settling
consumePromiseFive();

//above code will work if it is resolved but if rejected it will throw


error
//below is solution for that problem
//wrap the code which will throw error in try catch block
const promiseFive = new Promise(function (resolve, reject) {
setTimeout(() => {
let error = true;//error based checking
if (!error) {
resolve({ username: 'Hitesh', email: 'hitesh@[Link]', id:
2337 })
} else {
reject("ERROR: something went wrong")//gives error
//this is returned to the .catch()
}
}, 2000);
})

async function consumePromiseFive() {


try {
//wait till promiseFive is settled and store the return value in a
variable. gets from resolve or reject
const response = await promiseFive;
//promise is an object, that is why it is not consumed like
promiseFive();
[Link](response);
} catch (error) {
[Link](error)
}
}
//now you have to run this function for the promise to start settling
consumePromiseFive();

async function getAllUsers() {


//fetch is an object
//returns a promise
try {
//it is a network request so use await and it will return so store it
in a variable
const response = await
fetch('[Link] only url
// .ok Property: Always check [Link] before calling .json().
If the server returns a 404 (Not Found), [Link] will be false.
if (![Link]) {
throw new Error(`HTTP error! status: ${[Link]}`);
}
// Remember that [Link]() is also asynchronous and must
be awaited.
const data = await [Link]() //converts the returned data
from string to json
// You should use [Link]() when you have a raw string ready
in memory, and .json() when you are receiving a stream of data from
a network request.
[Link](data)
} catch (error) {
[Link]("E: ", error)
}
}
getAllUsers()

//above same code with .then() .catch()


fetch('[Link]
=> {
return [Link]()
}).then((data)=>{
[Link](data)
}).catch((error) => [Link]("E: ", error))

// By using return [Link](), you pass that Promise to the


next .then() block. The second .then() waits for that Promise to finish
before giving you the actual data.

//can also do this:


const response = await
fetch('[Link]
const data = await [Link](); // The 'await' makes it wait for
the data
[Link](data);
1. The async/await Method (Modern & Clean)
This is "syntactic sugar" built on top of Promises. It makes
asynchronous code look and behave like synchronous code.
How it works: await pauses the execution of the function until the
Promise settles (resolves or rejects).
Error Handling: Uses the standard try...catch blocks that you use in
regular JavaScript.
When to use:
This is the industry standard for modern projects.
Use it when you have dependent steps (e.g., you need the user ID
from the first request to make a second request).
It is much easier to read when your logic gets complex.
2. The .then() / .catch() Method (The Foundation)
This is the "Promise Chain" syntax.
How it works: It uses callbacks. Each .then() returns a new Promise,
allowing you to "pipe" data from one step to the next.
Error Handling: Uses a dedicated .catch() at the end of the chain to
catch errors from any previous step.
When to use:
When you are writing quick scripts or one-liners.
When you want to fire off a request but don't want to stop the rest of
the function execution (non-blocking).
Inside functional programming patterns (like mapping over an array
of URLs).

Key Differences at a Glance


Feature async/await .then() / .catch()

Readability Looks like a top-to- Can become "Callback


bottom list of tasks. Hell" if nested too
deeply.

Error Uses try/catch (very Uses .catch() (specific


Handling familiar). to Promises).

Debugging Easier to set Harder to debug as it


breakpoints on jumps between
specific lines. callbacks.

Conditionals Simple if/else works Requires wrapping


naturally. logic inside the .then().

One Critical Rule for Both


As you noted in your comments: fetch is a two-step process.
Step 1: Get the HTTP Response headers (The response object).
Step 2: Read the body stream to completion (The .json() method).
Both steps take time, which is why you either
need two awaits or two .then()s.

why fetch api if XMLHttpRequest was available?


The JavaScript Fetch API is a modern, promise-based interface used
for making HTTP requests (like fetching data from a server) in web
browsers and [Link] (version 18+). It provides a cleaner alternative
to the older XMLHttpRequest.
Basic Usage
The fetch() function takes one mandatory argument, the URL of the
resource you want to fetch, and returns a Promise that resolves to
a Response object.
Using async/await
For cleaner and more readable code, especially when dealing with
multiple asynchronous operations, you can use the async/await
Common Request Methods
You can configure the request by passing an optional options object
as the second argument to fetch().
GET: The default method. Used to retrieve data.
POST: Used to send data to the server (e.g., to create a new
resource).
PUT/PATCH: Used to update data on the server.
DELETE: Used to delete a resource.
Example of a POST request:
const postData = { title: 'New Post', body: 'This is a new post.', userId:
1 };

fetch('[Link] {
method: 'POST', // Specify the method
headers: {
'Content-Type': 'application/json' // Indicate the content type
},
body: [Link](postData) // Send the data as a JSON string
})
.then(response => [Link]())
.then(data => [Link]('Success:', data))
.catch(error => [Link]('Error:', error));
A POST request is used to send data to a server to create or update a
resource. Unlike a GET request (where data is sent in the URL), a
POST request carries its "payload" in the body of the HTTP message,
making it ideal for passwords, form data, or large JSON objects.
How the Code Works (Step-by-Step)
The fetch function takes two arguments: the URL and an options
object.
method: 'POST': Tells the browser this isn't a standard "read"
request. It tells the server, "I am bringing new data to save."
headers: This is like the label on a package. 'Content-Type':
'application/json' tells the server's API, "The data inside the body is
formatted as JSON, so please parse it as such." Without this, many
servers will ignore your data. MDN: Content-Type Header
body: [Link](postData):
The postData is a JavaScript object.
HTTP can only transport strings or binary data, not live JS objects.
[Link]() converts your object into a raw string: '{"title":"New
Post"..."}'.
The Response: After the server processes your data, it usually sends
back the newly created object (often with a new id) to confirm
success.
When to use POST?
Creating a new user or blog post.
Uploading files or images.
Submitting a login form (to keep credentials out of the URL history).
Watch out: A common mistake is forgetting to use [Link](). If
you pass a raw object to body, the request will likely fail with a "400
Bad Request" error.
This is better:
async function createPost() {
const postData = { title: 'New Post', body: 'This is a new post.',
userId: 1 };

try {
const response = await
fetch('[Link] {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: [Link](postData)
});

if (![Link]) throw new Error('Failed to create post');

const result = await [Link]();


[Link]('Success! New ID created:', [Link]);
} catch (error) {
[Link]('Error:', [Link]);
}
}
createPost();
*why?

//special queue if formed for fetch() and is is executed before task


queue and async await
Response = fetch(‘some-url’)
First things :
Goes to reserve space for variables and data
Data:-
onFulfilled[]
onRejection[]
//goes to global memory
Second thing:
Web browser/node:
Sends network request
Either data goes to network or dosent
//any response goes to resolve
If request does not go it goes to reject
Object oriented javascript
javascript is primarily a prototype based language

#OOP
Object-oriented programming (OOP) is a programming paradigm
based on the concept of "objects," which contain data (attributes)
and code (methods)

JavaScript is a heavily object-oriented language that follows a


prototype-based model but also offers a familiar class syntax
(introduced in ES6) for implementing traditional OOP paradigms.
OOP in JavaScript helps organize code, making it reusable, modular,
and easier to manage in large applications.
While JavaScript uses prototypes under the hood, the modern class
syntax is the standard way to implement the core principles of OOP:
Objects and Classes: An object is a collection of related data
(properties) and functions (methods). A class serves as a blueprint or
template for creating objects.
Encapsulation: This involves bundling the data (properties) and the
methods that operate on that data within a single unit (an object or
class), controlling access to internal details.
Inheritance: This allows a new class (child/derived class) to inherit
properties and methods from an existing class (parent/superclass),
promoting code reuse.
Polymorphism: This principle enables a single function or method
name to behave differently depending on the object it is called on,
usually achieved through method overriding in child classes.
Abstraction: This means hiding complex implementation details and
showing only the necessary features or a simplified interface to the
user.

##Object
collection of properties and methods

parts of OOP in js
object literal - const user = {}
constructor function
prototypes
classes
instances(new, this)
const user = {
//properties
username: 'hitesh',
logincount: 5,
age: 19,

//methods
getUserDetails: function () {
for (const key in this) {
// 1. Check if the key belongs to the object (not prototype)
// 2. Check if the value is NOT a function
if ([Link](this, key) && typeof this[key] !== 'function')
{
[Link](`${key} : ${this[key]}`);
}
}
}
}
//this keyword refers to current context

[Link]()

//constructor function
function User(username, age, course){
[Link] = username
[Link] = age
[Link] = course
return this
}

//if you do this it will overwrite values


const user1 = User('hitesh', 19, 'bca')
const user2 = User('tripti', 20, 'bca')

//so use new keyword


const user1 = new User('hitesh', 19, 'bca')
const user2 = new User('tripti', 20, 'bca')
[Link](user1)
[Link](user2)

// can check if a object is created from that function using instanceof


[Link](user1 instanceof User)//will print true

//prototype
//default behaviour of js - prototypal
function createUser(username, age){
[Link] = username
[Link] = age
}

//injecting prototypes
[Link] = function(username){
[Link] = username
}
[Link] = function(age){
[Link] = age
}
[Link] = function(){
for (const key in this) {
if ([Link](this, key) && typeof [Link] !== 'function'){
[Link](`${key} : ${this[key]}`)
}
}
}
//use new keyword, it will inject these protypes or it will give error
const me = new createUser('hitesh',19)
const sattu = new createUser('sattu',20)

[Link]()
[Link]()
/*

Here's what happens behind the scenes when the new keyword is
used:

A new object is created: The new keyword initiates the creation of a


new JavaScript object.

A prototype is linked: The newly created object gets linked to the


prototype property of the constructor function. This means that it
has access to properties and methods defined on the constructor's
prototype.

The constructor is called: The constructor function is called with the


specified arguments and this is bound to the newly created object. If
no explicit return value is specified from the constructor, JavaScript
assumes this, the newly created object, to be the intended return
value.

The new object is returned: After the constructor function has been
called, if it doesn't return a non-primitive value (object, array,
function, etc.), the newly created object is returned.

*/
//we can inject a function to the object directly so it is avilable for all
objects
[Link] = function(){
[Link]('this is function by hitesh')
}
[Link]()

//functions, arrays and strings all go through object datatype for


prototypes.
//so any method you inject to Object, will be available to all of these.
but if you inject in array it is not available in others or in object.

// inheritance in objects
const human ={
name:"hitesh"
}
const superHuman ={
hasSuperpower:true
}
const hero={
savesPeople:true
}
const villan ={
harmsPeople:true,
//__proto__ is used for inheritance
__proto__:superHuman//inherits properties of superHuman
}

hero.__proto__ = human
villan.__proto__ = human//overwrites the previous proto
// [Link](villan.__proto__.name)

//modern syntax
[Link](villan, superHuman)

[Link](villan.__proto__.hasSuperpower)//this also overwrites


the previous proto

//call and this


function setUsername(username){
[Link] = username
[Link]('username set',[Link])
}
function createPerson(username, email , password){
// setUsername(username)//this will call the function but it will
not set username for this context as it will be removed from call stack
after execution and its context will also be deleted
//so use .call() method, used for holding the reference
[Link](this, username)//Calls the function with the
specified object as the this value and the specified rest arguments as
the arguments.
[Link] = email
[Link] = password
}

const userOne = new


createPerson('hitesh','hitesh@[Link]','2337')
[Link](userOne)

//class constructor
the class keyword is used to create templates for building
objects with shared properties and methods, offering a cleaner
syntax for object-oriented programming (OOP) based on JavaScript's
existing prototype system
Key Components
constructor method: A special method that runs automatically when
a new object instance is created with the new keyword. It's used to
initialize object properties.
Properties (Fields): Variables that hold data. They can be public or
private (prefixed with #).
Methods: Functions defined within the class that define the object's
behavior.
static keyword: Used to define properties or methods that belong to
the class itself, rather than to an instance of the class.
class Dog {
#sound = "woof"; // Private field

constructor(name) {
[Link] = name; // Public property
}

bark() {
[Link](`${[Link]} says ${this.#sound}!`); // Method can
access private field
}
}

// Creating an object (instance) from the class


const myDog = new Dog("Buddy");

// Calling a method on the instance


[Link](); // Output: "Buddy says woof!"

// Trying to access the private field directly will cause an error


// [Link](myDog.#sound); // SyntaxError

//constructor is automatically called when using new keyword


class Human {
constructor(name, age){
[Link] = name
[Link] = age
}

displayDetails(){
for (const key in this) {
if (![Link](this, key)) continue;
[Link](`${key} : ${this[key]}`)
}
}
static createId(){//this method is not available to the instance of
this class ie. objects
return "123"
}

// const hitesh = new Human('hitesh', 19)


// [Link]()
// [Link](typeof hitesh)//prints object

//inheritance using class


class hero extends Human{
constructor(name, age, superpower){
super(name, age)//sends to the constructor of super class along
with the context of this class
[Link] = superpower
}
useSuperpower(){
[Link]('superpower used: ', [Link])
}
}
const Hulk = new hero('hulk', 30, 'smash')
//object for class cannot be created without new keyword
[Link]()
[Link]()
//use instanceof for checking if a object is made from a class
[Link](Hulk instanceof hero)//true
[Link](Hulk instanceof Human)//true

//bind
In JavaScript, the bind() method creates a new function that, when
called, has its this keyword set to a specific provided value.
Unlike call() or apply(), which execute a function
immediately, bind() "locks in" the context for future use.
const boundFunction = [Link](thisArg, arg1, arg2, ...);
thisArg: The value to be passed as this to the target function.
arg1, arg2, ...: Optional arguments to prepend to the parameters
when the bound function is invoked.
Common Use Cases
Fixing "Lost" Context: When you extract a method from an object to
use as a callback (like in setTimeout or an event listener), the
connection to the original object is lost. bind() restores it.

const person = {
name: "Alice",
greet: function() { [Link]("Hello, " + [Link]); }
};
const looseGreet = [Link];
looseGreet(); // "Hello, undefined" (lost context)
const boundGreet = [Link](person);
boundGreet(); // "Hello, Alice" (context restored)

Comparison Table

Feature call() bind()

Immediate Yes No
Invocation

Returns Function's result A new function

Common Use Borrowing Preserving context for


Case methods for event listeners
instant use or setTimeout

Arguments Passed Passed individually; can


individually be pre-filled (currying)
after thisArg

const user = { name: "Dev" };function greet(greeting) {


[Link](`${greeting}, ${[Link]}`);
}
// call() executes it right now
[Link](user, "Hello"); // Output: "Hello, Dev"
// bind() creates a reusable versionconst laterGreet = [Link](user,
"Welcome");
laterGreet(); // Output: "Welcome, Dev"

Key Differences
Execution: call() invokes the function immediately. bind() returns a
new function that you can store in a variable and call later.
Return Value: call() returns the result of the executed
function. bind() returns a copy of the original function with a fixed
context.
Persistence: bind() creates a permanent link between the function
and the this context, which cannot be overridden by subsequent
calls.
class React {
constructor(){
[Link] = 'React'
[Link] = '[Link]
//requirement
[Link]('.btn').addEventListener('click',
[Link](this/*here this refers to the context of
construcor so that they are available in handleClick() function*/))
}
handleClick(){
[Link]('button clicked')
[Link](this)
}
}
const app = new React()

More about objects


[Link]([Link])//will print 3.14
[Link] = 5
[Link]([Link])//still prints 3.14
//why ? why it is not changed?
Let mpi = [Link](Math, ‘PI’)
[Link](mpi)// will print some hidden properties of the PI
property
{
Value: 3.14,
Writable:false
//and many more
}
These properties are hardcoded and cannot be changed
We can also do this in our own objects
Const chai ={
name:’chai’,
price:250,
isAvailable:true
}
[Link]([Link](chai))//will print
undefined

const chai ={
name:'my chai',
price:250,
isAvailable:true
}
// [Link]([Link](chai))//will print
undefined
[Link]([Link](chai,'price'))//will
print hidden properties of name

[Link](chai, 'price',{
writable:false,//cannot change the value now
// enumerable:false//hides it from iterations
})
[Link]([Link](chai,'price'))//will
print hidden properties of name
for (const key in chai) {
if (![Link](chai, key)) continue;

const element = chai[key];

[Link](element)
}

//getter setters

Getter and setters are special methods used to define computed


properties and control access to an object’s data. It allows logic to be
executd when a property is accessed or modified.
//a getter method uses the get keyword and is automatically invoked
when you read a property’s value, but is accessed withour
parentheses like a regular property
//a setter method uses the set keuword and is automatically invoked
when you assign a value to a property. A setter must have exactly one
parameter(the value being assigned)

class Human {
constructor(name, age, id) {
[Link] = name
[Link] = age
[Link] = id??[Link]()
}

displayDetails() {
for (const key in this) {
if (![Link](this, key)) continue;
[Link](`${key} : ${this[key]}`)
}
}
// get id(){
// return [Link]
// }
// set id(value){
// [Link] = value
// }
//above get and set will give errors of max call stack full
//getter and setter name should be same as id
//if you defined a getter you have to define a setter or you will get
an error
get id(){
return this._id
}
set id(value){
this._id = value
}
static createId() {//this method is not available to the instance of
this class ie. objects
return "123"
}
}

const hitesh = new Human("hitesh", 20)


[Link](hitesh)
[Link]([Link])

//can also do same thing with the objects

//old method of getters and setters (before classes)


function User(name, age, password){
this._name = name
this._age = age
this._password = password

[Link](this,'name',{
get:function(){
return this._name
},
set:function(value){
this._name = value
}
})
[Link](this,'password',{
get:function(){
return this._password
},
set:function(value){
this._password = value
}
})
}

let sattu = new User('sattu',20, 'qwert')


[Link]([Link])
[Link]([Link])
[Link] = "jjjjj"
[Link]([Link])

//lexcal scope and closure


//lexical scoping
//inner function have access to the variables of outer function
function outer(){
let name = "hitesh"
function inner(){
[Link]('inner ',name)
}
inner()
}
outer()
// inner()// this will give error as inner is not defined because when
the context of outer was deleted, everything inside it got deleted.

//closure
function Big(){
let name = "kishan"
function small(){
[Link]('small ',name)
}
return small;//this will not only pass the reference of 'small'
function but also the lexical scope of "Big" function due to lexical
scoping
}
const my = Big()
my()//this will run as the context of outer function is available

*what is the real world senario where lexical scoping and closure
come in handy?

You might also like