0% found this document useful (0 votes)
28 views40 pages

Js Notes

The document provides an overview of JavaScript environments like Node.js, Deno, and Bun, and discusses fundamental concepts such as variables, data types, strings, numbers, arrays, objects, functions, and DOM manipulation. It highlights the differences between primitive and non-primitive data types, explains various methods and operations on strings and arrays, and introduces concepts like destructuring, arrow functions, and the call stack. Additionally, it covers loops, higher-order functions, and how to manipulate the DOM using JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views40 pages

Js Notes

The document provides an overview of JavaScript environments like Node.js, Deno, and Bun, and discusses fundamental concepts such as variables, data types, strings, numbers, arrays, objects, functions, and DOM manipulation. It highlights the differences between primitive and non-primitive data types, explains various methods and operations on strings and arrays, and introduces concepts like destructuring, arrow functions, and the call stack. Additionally, it covers loops, higher-order functions, and how to manipulate the DOM using JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 40

Node js and deno,bun are javascript enviornment which execute the js code alone

earlier we need to make index.html and then add script and


then write js in that script.

github is a platoform to store our work and collab with other to work as a open
source
it also provide codespace to work with js and others

*********************************variables and
constants******************************

variables are like container that holds some information /ḍata


const cannot be changed

let const var

const is immutable while let and var are mutable


let cannot be redeclared while var can be
let is blocked scope while var global scoped is not

********************************DATATYPES*************************************

*****Primitive:->stored in stack

String
number
bigint
boolean
NULL->stand alnoe value ->type = object
undefined:variable is declared but not yet defined type => undefined
symbol:to find uniqueness

USERDEFINED->referenced datatypes ->stored in heap


objects:

*data type conversion*

let score ="33"


let validnumber= Number(score)

score ->typeafter using Number(score)->value (console.log())

Number()

"33" -> number -> 33


"33abc" ->number ->nan
true->number -> 1
null->number -> 0
undefined -> number -> nan

Boolean()
1->boolean->true
0->boolean->false
""->boolean-> false
"bhacik"->boolean->true
**************DATATYPES***************************:
PRIMITIVE-> non reference type

string number null undefined symbol big int boolean

non primitive (reference types)

object array , function

js is dynamically type language

************************************************Strings****************************
************************

string interpolation : using backtick to wrtie string in which we can take


placeholder to inject value in between using dollar sign

ex:
let name = "Bhavik Rawal"
let repo=10
console.log(`my name is ${name} and my repo count is ${repo}`)

******string declaratoin new method

const str= new String('Bhavik')

******Some methods ******


toUppercase
charAt
indexOf
.substr(firstindex,length)
s.slice(firstindex,endindex) -> firstindex canbe negative ->slice we can use
negative
str.trim() remove extra space

**Replace""
const url = "https://hitesh.com/Bhavik%20rawal/
console.log(url.replace("%20","-");
url.includes(bhavik)

** split **

convert arr into string and split it on based on some char

let newstr= 'Bhavik-Rawal-is-my-name'


console.log(newstr.split('-'))
op->[Bhavik,rawal,is,my,name]

***********************************Numbers and
Math*******************************************

const score = 400


log(score)
op-> 400

js automatically detect it is number but we can explicitly give it as number


const score = new Number(100)
log(score)
op-> [Number:100]

10000000
log(score.toLocaleString('en-IND')
op 10,00,000

math.random -> between 0 and 1

console.log((Math.random()*10)+1) between 1 to 10
console.log(Math.floor(Math.random()*(max-min+1))+min)

*********************Date And Time**************************

Date is an object same as Number , String

let mydate = new Date()


console.log(mydate.toString()) -> wed mar 01 2023 12:05:19
console.log(mydate.toDateString()) wed mar 01 2023
console.log(mydate.toLocaleString()) 3/1/2023,12:05:19 pm

console.log(typeof mydate)
op->object

**creatibg our date


let mycreateddate= new Date(2023,0,23);
let mycrdate= new date Date("2023-01-14);
let mycrdate= new date Date(" 01-14-2023");
let mytimestamp= Date.now()

console.log(myCreateddate.toDateString());

mydate.gettime() give time in millisecond

timestamp= Date.now()

give currennt time in millisecond


to get in seconds
console.log(math.floor(date.now()/1000))

***********************Arrays***************

Array are oject that can store different elements of different tyoe in single
variable

js arrays:
1) resizable contain mix of datatypes
2)0 based index
3) copy of array create shallow copy

cosnt arr= [1,2,3,4,5,"bhavik"]


const arr = new Array(1,2,3,4,5,"bhavik")

**METHODS**
push(9) / unshift (9)
pop()/shift()

myarr.includes(9)
myarr.indexOf(4)

const newarr= myarr.join()


new arr will be bind with the myarr but the type of the newarr will be string not
arr

difference between slice and splice

1) slice extract a part of string | 1) splice extract a part of string


and parameters are first index | and parameters are first index
and last index while last index| and lastindex while last index
is not included | is included
|
2) slice doesnot modify the arr | 2) splice modify the whole arr

*** array in array


if we push array in array
array will become array of array
arr1.push(arr2)
=>[1,2,3,4,5,[6,7,8,9]]

to merge 2 array we use


1) concat -> (newarr= arr1.concat(arr2))
2) spread operator -> (newarr= [...arr1,...arr2])

Array.isArray("Bhavik") return false


Array.from("bhavik") -> return arr of bhavik['b','h','a','v','i','k']
Array.from({name:"Bhavik"}) -> return empty [] need to mention we need array from
key or value

************objects**************

objects can be created in two ways :


1) using literals
2) using constructor -> singleton object will be created ->more than one instance
cannot be created -> object.create()

literals:

const jsuser={
name:"bhavik",
email:"[email protected]",
age:18
}
juser.email="cajbds"
object.freeze(juser)
now juser is immutable

symbol : it is a primitive datatype used to make key unique


ex:
const sym=Symbol('id')
const juser{
name:"bhavik"
[sym]=123,
age=18
}
console.log(juser[sym])

*****Singleton object

const tinderuser= new Object()

*****non singleton object

const tinderuser ={}

tinderuser.id="123abc"
tinderuser.name="Samy"
tinderuser.isloggedin=false

*******OBJECT INSIDE OBJECT

const reguser={
email:"[email protected]",
fullname:{
userfullname:{
name:"bhavik",
lastname:"rawal",
}
}
}

console.log(reguser.fullname.userfullname.lastname)

merging objects->Object.assign(target,sources}

const obj1={0:"a",1:"b"}
const obj2={2:"a",3:"b"}
const obj3={4:"a",5:"b"}

const obj4=Object.assign({},obj1,obj2,obj3}

using spread operator

const obj4={...obj1,...obj2,...obj3}

some methods

Object.keys(tinderuser) return an array


object.values(tinderuser)
Object.entries(tinderuser)
tinderUser.hasOwnProperty('islogged')
Object.defineProperty()

******************destructuring************************
const course={
name:"Js"
price:999,
courseInstructor:"bhavik"
}

If we need to access this value multiple times


we do not want to write it multipletime so use destructuring

const{courseinstructor:ins}=course

console.log(ins)

******************************functions****************
syntax:

function name(){}

name ->reference ->when we do not want to execute directly later on on some evenets
name()->execution;

when we dont know the no of parameterd coming

function calculate(... num1){-> rest operator

return num1
}

calculate(100,200,300,400)
op->[100,200,300,400]

*******************************Scope*****************
var -> global scoped
let -> block scoped
const -> block scoped

****************************Arrow Functions*********************

this-> keyword is used to pint to the current context

value of this in browser is -> window object


value of this in node enviornment-> empty object
value of this in scope-> current context

we cannot use this in function

functoin chai(){
let username="Bhavik"
console.log(this.username)
}

chai()

op->undefined
Normal function Arrow Function

function greet (){} const greet=()=>{}

it have its own this inherit this from parent (lexical this)
accepet parameter do not accept parameter

******Arrow function
const chai =()=>{
const username="Bhavik Rawal"
console.log(this.username)
}
op->undefined

const addtwo= (num1,num2)=>{


return num1+num2
}
console.log(addtwo())

arrow function with implicit return

const addtwo (num1,num2)=> num1+num2

no need to use return keyword

************immediately invoke function expression*****************

ifee is used to immediately invoke a function and They are


typically used to create a local scope for variables to prevent
polluting the global scope variable.

syntax:

(definition of function)()

var globalVar = "I am global";

(function() {
var localVar = "I am local";
console.log(localVar); // Outputs: I am local
})();

console.log(globalVar); // Outputs: I am global


console.log(localVar); // Error: localVar is not defined

to end ifee we use semicolon at the end of ifee to make sure that
function is end here

***********************************how does js work behind the


scene*********************

**Javascript-> execution context

js run file into this 3 phase :


1)global execution phase
2)memory phase
3)execution phase

example :

let val1=10
let val2=5;
function addnum( num1,num2){
let total= num1+num2
return total
}

let res1=addnum(val1,val2)
let res2=addnum(10,2)

phases:
1)*** global execution->this keyword variable is allocated global

2)*** memory phase ->

1) val1->undefined
2) val2->undefined
3)addnum-> definition
4)res1-> undefined
5)res2->undefined

3)*** execution phase ->


1)val1=10;
2)val2=5;
3)add num-> a new varibale enviornmentis created + execution thread
**again 2 phase :
*memory phase:

num1->undefined
num2->undefined
total->undefined

*execution phase
num1=10
num2=5
total=15
return total to global context and delete newky created
enviornment

4)res1=15
5)addnum-> a new varibale enviornmentis created + execution thread
**again 2 phase :
*memory phase:

num1->undefined
num2->undefined
total->undefined

*execution phase
num1=10
num2=2
total=12
return total to global context and delete newky created
enviornment

6)res2=12

*************call stack**********
stack work on the base of lifo order
every function whenever is called goes on stack and when the function terminate
it is popped from stack
if we have function inside function then the call stack will hav both function
ex
one (){
two();
console.log(two compoleted)
}
call stack :

| two() |
| one() |
| global |
-----------

*************condition flow ***************

falsy value:

false,0,-0,"",big int -> 0n, null , undefined ,nan

truthy value:
all other than falsy value
"0" 'false'," ", [],{}, function (){}

nullish coalescing operator(??) : null undefined

let val1;
val1=5 ?? 10

if(respoonse is null or undefined )

val 1= if null or undefined than ?? other


val 1= null ?? 10
(val1 =10)

***************loops*****************
for(let i=0;i>10;i++){
console.log(i)
}

while(condition if true){
statement
increment
}
do{
} while(condition)
**************More Loops-Arrays specific loops********************

*****for of loops

["","",""]
[{},{},{}]

const arr= [1,2,3,4,5]

for(const iterator of object){


}

ex:

for (const num of arr){


console.log(num)
}

******maps*****->key value pair unique values


const map = new Map()
map.set('IN',"India)
map.set('USA',"United State of America")

for(const key of map){


console.log(key)
}
whole map will get printed

to print specific

for(const [key,value] of map){


console.log(key,':-', value)
}

const myobj={
'a'=1,
'b'=2,
'c'=3,
'd'=4
}

Object is not iteratable like this

const myobj={
'a'=1,
'b'=2,
'c'=3,
'd'=4
}

for in loop ->for objects

for(const key in myobj){

console.log(`${key} is the ${myobj[key]}`)


}

for array : key will print index

for each loop ->high order function

arrname.forEach(callback function)

call back function doesnot hace name

ex
const coding=["js",ruby","java"]

coding.forEach(function(item) {
console.log(item)
})

using arrow function

coding.forEach( (item)=>{
console.log(item)
})

or give reference of funciton

coding.forEach(printme)

function printme(item){
console.log(item)
}

coding.forEach((item,index,arr)=>{
console.log(item,index,arr)
})

for of loop | for in loop for each loop


|
can be used on | best for object best for arr
arr strings maps |
set not on object |
|
give value | give index take callback as parameter

function should be reference not


execution
and callback function do not hace name

high order function

do not returl values


********more on for each*********

**********Filter maps and reduce

const values= coding.forEach( (item) =>{


console.log(item)
return item;
}

console.log(values)
->undefeined

to return values use filter

condition in filter
const values= coding.filter((item)=> item>10)

********************* Map**************************

const myarr= [1,2,3,4,5,6,7,8,9]

cosnt newnums = myarr.map((num) => return num+10)


console.log(newnums)

***********Chaining***********
const newnums = myarr
.map((num)=> num*10 )
.map((num)=> num+1)
.filter((num) => nums>=40)

***********Reduce************

const nums= [1,2,3]

const mytotal=mynums.reduce(function (acc,currval) {


return acc+currval
},0)

console.log(mytotal)

const mytotal= nuums.reduce((acc,currval)=>{return acc+currval},0)

*********************************DOM MANIPUlATIONS***********************

windows ->document -> html->head


|
Body
document.getElementById('title')

doucment.getElementById('title').getAttribute('class')

doucment.getElementById('title').setAttribute('class','heading alkfn')

title.style.backgroundColor='green'

title.textcontent->give all the content including hidden


title.innerHTML->give HTML tags also
title.innerText->give only content which is visible

differnce between Textcontent and innertext

Feature | innerText |
textContent

Definition | Returns the visible text inside an element. |


Returns all text inside an

element (including hidden text).

Visibility | Ignores text from hidden elements (like with display: none). |
Includes text from hidden elements. text regardless of visibility.

**********queryselector******

queryselector gives the first element of the selected item

**********queryselectorAll******

queryselectorall give the node collection not array

const templist= document.querySelectorAll('h1')


templist.forEach((li)=>{

li.style.color='green'

})

***************Create a new Element**********

doc.body.childNodes->give all the child nodes including the


text comment

doc.body.children -> give thr collection of the nodes excluding


the text,comments
doc.body.firstElementChild->give first node

*******create element

const div= document.createElement('div') ,,,, 'h1','p'

div.className= "main"
div.id= 123

div.setAttribute("title","New title")

div.innertext="new elemnrt"
or
const addtext= document.createTextNode('new element')

div.appendchild(addtext)

doc.body.appendchild(div)

*****************edit and remove elemnt ************

*****Edit***
const secondlang=document.querySelector("li:nth-child(2)")

///secondlang.innerHTML="cpp"

optimized

const newli=document.creteElement('li')
newli.textcontent="mojo"

secondlang.replacewith(newli)

*********remove *********

const lastlang= document.queryselector('li:last-child')


lastlang.remove()

***************EVENTS IN JS************

Every events in js runs sequentially


events are some action on browser

document.getelemetbyid("owl").onclick= function(){
alert("owl clicked")->not good approach

use eventlistener ->give propogation functionality

best approach :

doc.getElementById('owl').addEventListener('click',()=>{
alert('owl clicked again')
},false)

some eventlistener
click
doubleclick

*********event object**********

document.getElementbyid('owl').addEventListener('click',function(e){

},false) if false ->event bubling else even capturing

type
timestamp
defaultprevented
target toelement
srcElement, currtarget
clientx, client y, screenx, screeny

alteky,ctrlkey,shiftkey,keycode

************event Propogation************

1) Event bubbling : In event bubbling the events propogate form the child
element to parent element , when the third parameter inside the event is false

document.getElementById('images').addEventListener('click',function(e){
console.log("clicked inside the ul")
},false)

document.getElementById('owl').addEventListener('click',function(e){
console.log("owl clicked")
},false)

"owl is inside the images"

op->owl clicked
clicked inside image

2) Event Capturing : in event capturing the event propogate from the parent node
to child node , happens when the third parameter is true

document.getElementById('images').addEventListener('click',function(e){
console.log("clicked inside the ul")
},true)

document.getElementById('owl').addEventListener('click',function(e){
console.log("owl clicked")
},true)
***** To Stop bubbling ******
we use
e.stopPropogation()

practice: when you clicked on image the image get remove

document.queryselector('#image').addeventListener('click',function(e){
if(e.target.tagName==='IMG'){
let removeit= e.target.parentNode;
removeit.remove();
}
}

************JAVASCRIPT ASYNC CODE*************

***********theoritical*********

Javascript is a synchronous(one code at a time ) and single threaded language

default js behaviour
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

blocking code vs non blocking code

block the flow pf program |||| do not block the execution

read file sync |||| read file async

js engine -> memory heap+ call stack

*************Event loop *********

The event loop in JavaScript is how JS handles multiple operations


at the same time, even though JavaScript itself is single-threaded
(it can only do one thing at a time).
Here's the basic idea:

Call Stack:

JS runs your code line by line in a stack.

If you call a function, it gets pushed onto the stack.


When the function finishes, it's popped off.

Web APIs (browser):

Some functions like setTimeout, fetch, or event listeners


are handled outside the call stack by the browser.

Example: when you write setTimeout(() => {...}, 1000), the timer
is managed by the browser. register callback

Callback Queue (Task Queue):

Once the browser is done with something (like after 1 second


for setTimeout), it puts your callback function into a queue.

Event Loop:

The event loop keeps checking: "Is the call stack empty?"

If yes, it takes the first thing from the callback queue and
pushes it onto the call stack to run.

***********timeout Function************

settimeout function:->method that are provided by browser,this is


used to execute some statement after some time

settimeout(()=>{

console.log("Bhavik")

},2000)

setinterval->method providded by browser , this is used to execute


the statement repeatedly in an interal

to stop settimeout use clear timeout

const change= setTimeout(()=>{


doc.queryselector('h1').innerHTML="best"
},2000)

clearTimeout(change)

*****************API REQUEST AND V8 ENGINE*********************

API-> is a interface between 2 systems

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: #212121;">
0 UNSENT Client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are
available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
</body>
<script>
const requestUrl = 'https://api.github.com/users/hiteshchoudhary'
const xhr = new XMLHttpRequest();
xhr.open('GET', requestUrl)
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
if (xhr.readyState === 4) {
const data = JSON.parse(this.responseText)
console.log(typeof data);
console.log(data.followers);
}
}
xhr.send();
</script>
</html>

************Promises*****************-> promises ar the promise of giving result no


matter if it is executed or not
-> it is a solution to callback hell(when a function is called in function )

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


//Do an async task
// DB calls, cryptography, network
setTimeout(function(){
console.log('Async task is compelete');
resolve()
}, 1000)
})

promiseOne.then(function(){
console.log("Promise consumed");
})

new Promise(function(resolve, reject){


setTimeout(function(){
console.log("Async task 2");
resolve()
}, 1000)

}).then(function(){
console.log("Async 2 resolved");
})

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


setTimeout(function(){
resolve({username: "Chai", email: "[email protected]"})
}, 1000)
})

promiseThree.then(function(user){
console.log(user);
})

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


setTimeout(function(){
let error = true
if (!error) {
resolve({username: "hitesh", password: "123"})
} else {
reject('ERROR: Something went wrong')
}
}, 1000)
})

promiseFour
.then((user) => {
console.log(user);
return user.username
}).then((username) => {
console.log(username);
}).catch(function(error){
console.log(error);
}).finally(() => console.log("The promise is either resolved or rejected"))

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


setTimeout(function(){
let error = true
if (!error) {
resolve({username: "javascript", password: "123"})
} else {
reject('ERROR: JS went wrong')
}
}, 1000)
});

async function consumePromiseFive(){


try {
const response = await promiseFive
console.log(response);
} catch (error) {
console.log(error);
}
}

consumePromiseFive()

// async function getAllUsers(){


// try {
// const response = await
fetch('https://jsonplaceholder.typicode.com/users')

// const data = await response.json()


// console.log(data);
// } catch (error) {
// console.log("E: ", error);
// }
// }

//getAllUsers()

fetch('https://api.github.com/users/hiteshchoudhary')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data);
})
.catch((error) => console.log(error))

// promise.all
// yes this is also available, kuch reading aap b kro.

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.

promise.all

const promise1 = Promise.resolve(3);


const promise2 = new Promise((resolve,reject)=>{
const val=false;
if(val){
resolve('promise is resolved')
}
else{
reject('Promise is rejected')
}
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "foo");
});

Promise.all([promise1, promise2, promise3]).then((values) => {


console.log(values);
})
.catch(()=>console.log("error in one of the promise"))

promise.allSettled

const promise1 = Promise.resolve(3);


const promise2 = new Promise((resolve,reject)=>{
const val=false;
if(val){
resolve('promise is resolved')
}
else{
reject('Promise is rejected')
}
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "foo");
});

Promise.allSettled([promise1, promise2, promise3])


.then(results => console.log(results));

**********fetch api**********

The Fetch API in JavaScript is a modern way to make network requests — like getting
data from a server, posting data, etc.
It replaces the older XMLHttpRequest method, making things cleaner and more
powerful.

How Fetch Works:


You call fetch() with a URL (and sometimes options like method, headers, body,
etc.)

It returns a Promise.

You use .then() to handle the response.

Basic Example:

fetch('https://api.example.com/data')
.then(response => response.json()) // convert response into JSON
.then(data => console.log(data)) // handle the data
.catch(error => console.error('Error:', error)); // handle errors

How fetch flow looks:


fetch() sends the request.

Server responds.

fetch() Promise resolves, even if it's a 404 or 500 error (you have to manually
check response.ok).

You typically convert the response using .json(), .text(), or .blob().


You handle the result or error.

Example with POST request:


javascript
Copy
Edit
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Bhavik', age: 21 })
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
Important points:
By default, fetch uses GET method.

Fetch won't reject the Promise for HTTP errors like 404 or 500. You need to check
response.ok.

Error handling mainly catches network failures (like no internet).

****************Object Oriented JS*************

Javascript is not object oriented language but it is a prototype


based language

it is similar to object oriented programming language has syntatic sugar

***** Parts of oops


object literals ->simply objects

construcor function -> give new coopy original is not affected usnign new we get
constructor
prototypes
classes
instances(new,this)

****4 pillar abstraction , inheritance , encapsulation , polymorphism

this
in nodejs enviornment -> empty object
in browser-> window object
in object -> current context
in function-> in nodejs-> global={}, int browser-> window

used to differentiate the curr variabel and parameter variable


function User(username, loginCount, isLoggedIn){
this.username = username;
this.loginCount = loginCount;
this.isLoggedIn = isLoggedIn

this.greeting = function(){
console.log(`Welcome ${this.username}`);

return this
}

const userOne = User("hitesh", 12, true)


const userTwo = User("ChaiAurCode", 11, false)
console.log(userOne);

here usertwo will overwrite the code of userone


problem

:::
****therefore****
**********Constructor*****
function User(username, loginCount, isLoggedIn){
this.username = username;
this.loginCount = loginCount;
this.isLoggedIn = isLoggedIn

this.greeting = function(){
console.log(`Welcome ${this.username}`);

return this // by default implicirt return no need to write


}

const userOne = new User("hitesh", 12, true)


const userTwo = new User("ChaiAurCode", 11, false)
console.log(userOne.constructor);
//console.log(userTwo);

**new-> new keyword create empty object called instance

1) new object is created


2) constructor fucntion is called
3) all argument are injected in this

************Magic of Prototype explaining new keyword **************

default behaviour of js is prototypple behaviour means js


do not give up it goes above the layer child to parent to
grand parent till null is not find

this, new and classes , prototyple inheritance is because of prototype

(Array->object ->NULL)
String -> object ->NULL)

function is function as well as object

function->object->NULL

function createUser(username,score){
this.username= username
this.score=score
}

function multipleBy5(num){

return num*5
}

multipleBy5.power = 2

console.log(multipleBy5(5));
console.log(multipleBy5.power);
console.log(multipleBy5.prototype);

function createUser(username, score){


this.username = username
this.score = score
}

createUser.prototype.increment = function(){
this.score++
}

createUser.prototype.printMe = function(){
console.log(`price is ${this.score}`);
}

const chai = new createUser("chai", 25)


const tea = createUser("tea", 250)

if new keyword is not used than it will not work as now of


the function in prototype is not yet linked with anuone
as soon as we use new keyword the function and prototype is linked
with the object

chai.printMe()

/*

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.

*/

*********Prototype************

// let myName = "hitesh "


// let mychannel = "chai "

// console.log(myName.trueLength);
no function of truelength if we want to create for all the string

let myHeros = ["thor", "spiderman"]

let heroPower = {
thor: "hammer",
spiderman: "sling",

getSpiderPower: function(){
console.log(`Spidy power is ${this.spiderman}`);
}
}

Object.prototype.hitesh = function(){
console.log(`hitesh is present in all objects`);
}

Array.prototype.heyHitesh = function(){
console.log(`Hitesh says hello`);
}

// heroPower.hitesh()
// myHeros.hitesh()
// myHeros.heyHitesh()
// heroPower.heyHitesh()

// inheritance

const User = {
name: "chai",
email: "[email protected]"
}
const Teacher = {
makeVideo: true
}

const TeachingSupport = {
isAvailable: false
}

const TASupport = {
makeAssignment: 'JS assignment',
fullTime: true,
__proto__: TeachingSupport
}

Teacher.__proto__ = User

// modern syntax
Object.setPrototypeOf(TeachingSupport, Teacher)

let anotherUsername = "ChaiAurCode "

String.prototype.trueLength = function(){
console.log(`${this}`);
console.log(`True length is: ${this.trim().length}`);
}

anotherUsername.trueLength()
"hitesh".trueLength()
"iceTea".trueLength()

******CALL*********

| callme() |
| fn | function(){
| fn | callme()
| fn | }
| fn |
| fn |
| global ec | browser =(this= window)
|--------------| node=(this={}) empty

call me function is inside the function


then this of call me will be bind whose context

it will bind with the global execution context

function SetUsername(username){
//complex DB calls
this.username = username
console.log("called");
}
function createUser(username, email, password){
SetUsername(username)

this.email = email
this.password = password
}

const chai = new createUser("chai", "[email protected]", "123")


console.log(chai);

In the above code, when we call SetUsername(username), the function is invoked as a


normal function.

Therefore, this inside SetUsername refers to the global object (window in browser,
or global in Node).

So username is assigned to the global object, not to the new object being created
by createUser.

When the SetUsername function ends, its local context is destroyed.

To avoid this, we should use .call(this, username) so that we explicitly set this
inside SetUsername to the current object being constructed by createUser.

This way, the username property gets properly attached to the new object.

Corrected Code:
javascript

function SetUsername(username){
this.username = username;
console.log("called");
}

function createUser(username, email, password){


SetUsername.call(this, username); // Pass the correct context

this.email = email;
this.password = password;
}

const chai = new createUser("chai", "[email protected]", "123");


console.log(chai);
Output:
pgsql
Copy
Edit
called
createUser { username: 'chai', email: '[email protected]', password: '123' }
What happens if you remove new and just call:

const chai = createUser("chai", "[email protected]", "123");


console.log(chai);
Step-by-Step What Happens:
When you don't use new:

The createUser function is called like a normal function, NOT as a constructor.

Therefore, this inside createUser is not a new object.

In browser (non-strict mode), this will point to the window object (global object).

So inside createUser:

SetUsername.call(this, username) — now this is the window object.

So window.username = "chai".

this.email = email; → window.email = "[email protected]"

this.password = password; → window.password = "123"

createUser function doesn’t return anything, so chai becomes undefined!

***********Classes******************

Es6

class User{

constructor(username,email,password){

this.username=username;
this.email=email;
this.password=password;
}

encryptPassword(){

return `${this.password}abc;

}
changeUsername(){
return `${this.username.toUpperCase()}`
}

};

const chai= new User('Bhavik','[email protected]',1234)


console.log(chai.encryptPassword())
console.log(chai.changeUsername())
/////Behind The scene

function User(username,email,password){

this.username=username;
this.email=email;
this.password=password;
}
User.prototype.encryptPassword= function(){
return `${this.password}abc;
}

User.prototype.changeUsername(){
return `${this.username.toUpperCase()}`
}

const chai= new User('Bhavik','[email protected]',1234)


console.log(chai.encryptPassword())
console.log(chai.changeUsername())

********inheritance**************]
class USer{

constructor(username){
this.username=username;
}

logme(){
console.log(this.username);
}

class Teacher extends User{


constructor(username,email,pass){
super(username)
this.email=email
this.password=password
}

addCourse(){
console.log('New Course is addded by ${this.username})`;
}

const chai= new teacher("chai","[email protected]",1234);


const masalachai= new user("masalachai")

masalachai.addcourse() -> error


chai.addcourse()->no error
masalachai.logMe()-> no error
chai.logMe() -> no error

console.log(chai===masalachai) false
console.log(chai=== teacher) false
console.log(chai instance of teacher) true
console.log(chai instacne of user) true

*******Behind the scene*********


// Parent constructor function
function User(username) {
this.username = username;
}

// Adding methods to User prototype


User.prototype.logme = function() {
console.log(this.username);
};

// Child constructor function


function Teacher(username, email, password) {
// Call the User constructor to initialize username
User.call(this, username);

// Initialize Teacher specific properties


this.email = email;
this.password = password;
}

// Inherit from User


Teacher.prototype = Object.create(User.prototype);

// Correct the constructor pointer


Teacher.prototype.constructor = Teacher;

// Add methods to Teacher prototype


Teacher.prototype.addCourse = function() {
console.log(`New Course is added by ${this.username}`);
};

// Usage
const chai = new Teacher("chai", "[email protected]", 1234);
const masalachai = new User("masalachai");

// masalachai.addCourse(); // error -> because addCourse() is not in User


// chai.addCourse(); // no error
// masalachai.logme(); // no error
// chai.logme(); // no error

**********Static Properties***********

Static Keyword is used to make a function private


it cannot be accessed easily outside

class User {
constructor(username){
this.username = username
}
logMe(){
console.log(`Username: ${this.username}`);
}

static createId(){
return `123`
}
}

const hitesh = new User("hitesh")


// console.log(hitesh.createId())->Not accessible

class Teacher extends User {


constructor(username, email){
super(username)
this.email = email
}
}

const iphone = new Teacher("iphone", "[email protected]")


console.log(iphone.createId());->Not accessible

************BIND************

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React</title>
</head>
<body>
<button>Button Clicked</button>
</body>
<script>
class React {
constructor(){
this.library = "React"
this.server = "https://localhost:300"

//requirement
document
.querySelector('button')
.addEventListener('click', this.handleClick.bind(this))
this is context of the app object now to get server in the
handleclick we need to pass this (app object ) else in handle click
the object will be either the global scoped / window in browser
or dom

}
handleClick(){
console.log("button clicked");
console.log(this.server);
}
}

const app = new React()


</script>
</html>

You made a class React, which when constructed:

Sets this.library = "React"

Sets this.server = "https://localhost:300"

Then adds an event listener on the button:

document.querySelector('button')
.addEventListener('click', this.handleClick.bind(this))
Second:

You have a method inside the class:

handleClick() {
console.log("button clicked");
console.log(this.server);
}
✅ Now the main point: Why .bind(this) is needed?

When the browser calls the event listener function (the handleClick method), it
does NOT automatically know that it should use your React class instance (app) as
this.

By default, when a normal function is called (NOT an arrow function):

this becomes undefined in strict mode or

this becomes the button itself (DOM element) in non-strict mode.

⚡ Problem without .bind(this)


If you didn't bind it, inside handleClick, this.server would be undefined because
this would refer to the button, not your React object.

bind(this) solves this by manually fixing the this inside handleClick to always
point to the instance of your React class (app), no matter who calls it later.

👉 In simple words:
bind(this) locks this to always mean your class object.

🔎 Visualization of What Happens

Without bind With bind(this)


this inside handleClick = button this inside handleClick = app object
this.server → undefined this.server → "https://localhost:300"
error or wrong output correct server printed
Super Quick Example to Understand bind
javascript
Copy
Edit
function sayHello() {
console.log(this.name);
}
const user = { name: "Bhavik" };

// Direct call
sayHello(); // undefined (because this = window)

// Bound call
const sayHelloUser = sayHello.bind(user);
sayHelloUser(); // Bhavik
See? bind glued this to the user object.

🔥 In your code:
When you click the button:

handleClick is called

this still correctly points to your React object (because of bind(this))

So you get the correct output:

button clicked
https://localhost:300

You said:
in this given codee user act as an object and this is user

ChatGPT said:
Yes Bhavik, you are absolutely correct! 💯
Let’s slow it down a bit and break it carefully:

In the small example I gave:

javascript
Copy
Edit
function sayHello() {
console.log(this.name);
}

const user = { name: "Bhavik" };

const sayHelloUser = sayHello.bind(user);


sayHelloUser(); // Bhavik
✅ Here:

user is just a normal object: { name: "Bhavik" }

When we do sayHello.bind(user), we're saying: 👉 "Hey, whenever sayHelloUser() is


called,
👉 inside that function, this should always mean user."

Thus, this = user inside the function.


Now, connect it to your original big React example:

In your big code, the React class object (app) is like the user.

You do this.handleClick.bind(this), so this inside handleClick always points to the


app object (not button).

🔥 One Line Summary:


In both cases:

You bind an object (whether user or app) to a function,

So that inside that function, this will always refer to that object.

*********MAthpi.js*********

*********OBJECT******

to find the propertys of some object '


const descriptor=Object.getOwnPropertyDescriptor(Math,"pi")

output:->
{
value:3.1459,
writable:false,
enumerable:false,
configurable:false
}

const chai={
name:'ginger chai',
price:250,
isAvailable:true
}
console.log(chai)

const descripter = Object.getOwnPropertyDescriptor(Math, "PI")

// console.log(descripter);

// console.log(Math.PI);
// Math.PI = 5
// console.log(Math.PI);

const chai = {
name: 'ginger chai',
price: 250,
isAvailable: true,

orderChai: function(){
console.log("chai nhi bni");
}
}
console.log(Object.getOwnPropertyDescriptor(chai, "name"));

Object.defineProperty(chai, 'name', {
//writable: false,
enumerable: true,

})

console.log(Object.getOwnPropertyDescriptor(chai, "name"));

for (let [key, value] of Object.entries(chai)) {


if (typeof value !== 'function') {

console.log(`${key} : ${value}`);
}
}

*******Getter and Setter in js


class User{
constructor(email,pass){
this.email=email
this.pass=pass
}
}
const bhavik= new User("[email protected]",1234);
console.log(bhavik.pass)

if( we dont want to give access to anyone ) use getter setter

class User{
constructor(email,pass){
this.email=email
this.pass=pass

get pass(){
return this._pass.toUpperCase() -> cannot use
this.pass.toUppercase() the
}
set pass(value){
this._pass=value
}
now if you have getter and setter is must without setter
it will throw error

}
const bhavik= new User("[email protected]",1234);
console.log(bhavik.pass)

**************gpt**********

✅ First, the code overview:


js
Copy
Edit
class User {
constructor(email, pass) {
this.email = email;
this.pass = pass; // This invokes the setter: set pass(value)
}

get pass() {
return this._pass.toUpperCase(); // This invokes the getter
}

set pass(value) {
this._pass = value; // This sets the private-like property _pass
}
}

const bhavik = new User("[email protected]", 1234);


console.log(bhavik.pass);
🔍 What’s happening step-by-step:
Constructor is called:

js
Copy
Edit
const bhavik = new User("[email protected]", 1234);
this.email = email → directly sets email.

this.pass = pass → looks like a normal assignment, but this calls the setter:

js
Copy
Edit
set pass(value) {
this._pass = value;
}
Getter is used when you access bhavik.pass:

js
Copy
Edit
console.log(bhavik.pass);
This calls:

js
Copy
Edit
get pass() {
return this._pass.toUpperCase();
}
⚠️ Common Confusion — Why can't we do this.pass.toUpperCase() inside the getter?
If inside the getter you write:

js
Copy
Edit
return this.pass.toUpperCase(); // ❌ Wrong
You’ll get an infinite recursive call error because:

this.pass will call the getter again,

which tries to call this.pass again,


and again...

💥 Stack overflow!

✅ Correct way is:

js
Copy
Edit
return this._pass.toUpperCase();
You use _pass, a backing variable, to avoid calling the getter again.

🔐 Why use a setter at all?


If you don’t define a setter, and you try:

this.pass = pass;
in the constructor or anywhere else, JavaScript won't know how to assign it, and
it'll throw an error like:

Cannot set property pass of #<User> which has only a getter


So if you define a getter, you must also define a setter to allow assignments.

**************** gpt end*************

function User(email, password){


this._email = email;
this._password = password

Object.defineProperty(this, 'email', {
get: function(){
return this._email.toUpperCase()
},
set: function(value){
this._email = value
}
})
Object.defineProperty(this, 'password', {
get: function(){
return this._password.toUpperCase()
},
set: function(value){
this._password = value
}
})

const chai = new User("[email protected]", "chai")

console.log(chai.email);

const User = {
_email: '[email protected]',
_password: "abc",

get email(){
return this._email.toUpperCase()
},

set email(value){
this._email = value
}
}

const tea = Object.create(User)


console.log(tea.email);

**************Lexical Scoping*********

function outer(){

let username="Bhavik"
function inner(){
console.log(username)->>>> accessible
}
inner()
}

outer()
console.log(username)-> no accessible

if there is a inner function inside a outer function than the variables of outer
function
are accessible in inner function this is called lexical scoping

***************closure************

when we return an inner function then not only function is returned


function along with lexical variables are also returned
this is closure

A closure is the combination of a function bundled together (enclosed)


with references to its surrounding state (the lexical environment).
In other words, a closure gives a function access to its outer scope.
In JavaScript, closures are created every time a function is created, at function
creation time.

example:
function makeFunc() {
const name = "Mozilla";
function displayName() {
console.log(name);
}
return displayName; -> returning fucntion displayname with its reference
variable -> ( lexical variables)
}

const myFunc = makeFunc();


myFunc();

************closure real world scenarion*******

<script>
// document.getElementById("orange").onclick = function(){
// document.body.style.backgroundColor = `orange`
// }
// document.getElementById("green").onclick = function(){
// document.body.style.backgroundColor = `green`
// }

function clickHandler(color){
// document.body.style.backgroundColor = `${color}`

return function(){
document.body.style.backgroundColor = `${color}`
}
}

document.getElementById('orange').onclick = clickHandler("orange")
document.getElementById('green').onclick = clickHandler("green")

</script>

You might also like