Js Notes
Js Notes
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******************************
********************************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
Number()
Boolean()
1->boolean->true
0->boolean->false
""->boolean-> false
"bhacik"->boolean->true
**************DATATYPES***************************:
PRIMITIVE-> non reference type
************************************************Strings****************************
************************
ex:
let name = "Bhavik Rawal"
let repo=10
console.log(`my name is ${name} and my repo count is ${repo}`)
**Replace""
const url = "https://hitesh.com/Bhavik%20rawal/
console.log(url.replace("%20","-");
url.includes(bhavik)
** split **
***********************************Numbers and
Math*******************************************
10000000
log(score.toLocaleString('en-IND')
op 10,00,000
console.log((Math.random()*10)+1) between 1 to 10
console.log(Math.floor(Math.random()*(max-min+1))+min)
console.log(typeof mydate)
op->object
console.log(myCreateddate.toDateString());
timestamp= Date.now()
***********************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
**METHODS**
push(9) / unshift (9)
pop()/shift()
myarr.includes(9)
myarr.indexOf(4)
************objects**************
literals:
const jsuser={
name:"bhavik",
email:"[email protected]",
age:18
}
juser.email="cajbds"
object.freeze(juser)
now juser is immutable
*****Singleton object
tinderuser.id="123abc"
tinderuser.name="Samy"
tinderuser.isloggedin=false
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}
const obj4={...obj1,...obj2,...obj3}
some methods
******************destructuring************************
const course={
name:"Js"
price:999,
courseInstructor:"bhavik"
}
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;
return num1
}
calculate(100,200,300,400)
op->[100,200,300,400]
*******************************Scope*****************
var -> global scoped
let -> block scoped
const -> block scoped
****************************Arrow Functions*********************
functoin chai(){
let username="Bhavik"
console.log(this.username)
}
chai()
op->undefined
Normal function Arrow Function
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
syntax:
(definition of function)()
(function() {
var localVar = "I am local";
console.log(localVar); // Outputs: I am local
})();
to end ifee we use semicolon at the end of ifee to make sure that
function is end here
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
1) val1->undefined
2) val2->undefined
3)addnum-> definition
4)res1-> undefined
5)res2->undefined
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 |
-----------
falsy value:
truthy value:
all other than falsy value
"0" 'false'," ", [],{}, function (){}
let val1;
val1=5 ?? 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
["","",""]
[{},{},{}]
ex:
to print specific
const myobj={
'a'=1,
'b'=2,
'c'=3,
'd'=4
}
const myobj={
'a'=1,
'b'=2,
'c'=3,
'd'=4
}
arrname.forEach(callback function)
ex
const coding=["js",ruby","java"]
coding.forEach(function(item) {
console.log(item)
})
coding.forEach( (item)=>{
console.log(item)
})
coding.forEach(printme)
function printme(item){
console.log(item)
}
coding.forEach((item,index,arr)=>{
console.log(item,index,arr)
})
console.log(values)
->undefeined
condition in filter
const values= coding.filter((item)=> item>10)
********************* Map**************************
***********Chaining***********
const newnums = myarr
.map((num)=> num*10 )
.map((num)=> num+1)
.filter((num) => nums>=40)
***********Reduce************
console.log(mytotal)
*********************************DOM MANIPUlATIONS***********************
doucment.getElementById('title').getAttribute('class')
doucment.getElementById('title').setAttribute('class','heading alkfn')
title.style.backgroundColor='green'
Feature | innerText |
textContent
Visibility | Ignores text from hidden elements (like with display: none). |
Includes text from hidden elements. text regardless of visibility.
**********queryselector******
**********queryselectorAll******
li.style.color='green'
})
*******create element
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***
const secondlang=document.querySelector("li:nth-child(2)")
///secondlang.innerHTML="cpp"
optimized
const newli=document.creteElement('li')
newli.textcontent="mojo"
secondlang.replacewith(newli)
*********remove *********
***************EVENTS IN JS************
document.getelemetbyid("owl").onclick= function(){
alert("owl clicked")->not good approach
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){
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)
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()
document.queryselector('#image').addeventListener('click',function(e){
if(e.target.tagName==='IMG'){
let removeit= e.target.parentNode;
removeit.remove();
}
}
***********theoritical*********
default js behaviour
execution context:
Call Stack:
Example: when you write setTimeout(() => {...}, 1000), the timer
is managed by the browser. register callback
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(()=>{
console.log("Bhavik")
},2000)
clearTimeout(change)
<!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>
promiseOne.then(function(){
console.log("Promise consumed");
})
}).then(function(){
console.log("Async 2 resolved");
})
promiseThree.then(function(user){
console.log(user);
})
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"))
consumePromiseFive()
//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.
promise.all
promise.allSettled
**********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.
It returns a Promise.
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
Server responds.
fetch() Promise resolves, even if it's a 404 or 500 error (you have to manually
check response.ok).
Fetch won't reject the Promise for HTTP errors like 404 or 500. You need to check
response.ok.
construcor function -> give new coopy original is not affected usnign new we get
constructor
prototypes
classes
instances(new,this)
this
in nodejs enviornment -> empty object
in browser-> window object
in object -> current context
in function-> in nodejs-> global={}, int browser-> window
this.greeting = function(){
console.log(`Welcome ${this.username}`);
return this
}
:::
****therefore****
**********Constructor*****
function User(username, loginCount, isLoggedIn){
this.username = username;
this.loginCount = loginCount;
this.isLoggedIn = isLoggedIn
this.greeting = function(){
console.log(`Welcome ${this.username}`);
(Array->object ->NULL)
String -> object ->NULL)
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);
createUser.prototype.increment = function(){
this.score++
}
createUser.prototype.printMe = function(){
console.log(`price is ${this.score}`);
}
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************
// console.log(myName.trueLength);
no function of truelength if we want to create for all the string
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)
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
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
}
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.
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");
}
this.email = email;
this.password = password;
}
In browser (non-strict mode), this will point to the window object (global object).
So inside createUser:
So window.username = "chai".
***********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()}`
}
};
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()}`
}
********inheritance**************]
class USer{
constructor(username){
this.username=username;
}
logme(){
console.log(this.username);
}
addCourse(){
console.log('New Course is addded by ${this.username})`;
}
console.log(chai===masalachai) false
console.log(chai=== teacher) false
console.log(chai instance of teacher) true
console.log(chai instacne of user) true
// Usage
const chai = new Teacher("chai", "[email protected]", 1234);
const masalachai = new User("masalachai");
**********Static Properties***********
class User {
constructor(username){
this.username = username
}
logMe(){
console.log(`Username: ${this.username}`);
}
static createId(){
return `123`
}
}
************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);
}
}
document.querySelector('button')
.addEventListener('click', this.handleClick.bind(this))
Second:
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.
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.
// 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
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:
javascript
Copy
Edit
function sayHello() {
console.log(this.name);
}
In your big code, the React class object (app) is like the user.
So that inside that function, this will always refer to that object.
*********MAthpi.js*********
*********OBJECT******
output:->
{
value:3.1459,
writable:false,
enumerable:false,
configurable:false
}
const chai={
name:'ginger chai',
price:250,
isAvailable:true
}
console.log(chai)
// 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"));
console.log(`${key} : ${value}`);
}
}
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**********
get pass() {
return this._pass.toUpperCase(); // This invokes the getter
}
set pass(value) {
this._pass = value; // This sets the private-like property _pass
}
}
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:
💥 Stack overflow!
js
Copy
Edit
return this._pass.toUpperCase();
You use _pass, a backing variable, to avoid calling the getter again.
this.pass = pass;
in the constructor or anywhere else, JavaScript won't know how to assign it, and
it'll throw an error like:
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
}
})
console.log(chai.email);
const User = {
_email: '[email protected]',
_password: "abc",
get email(){
return this._email.toUpperCase()
},
set email(value){
this._email = value
}
}
**************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************
example:
function makeFunc() {
const name = "Mozilla";
function displayName() {
console.log(name);
}
return displayName; -> returning fucntion displayname with its reference
variable -> ( lexical variables)
}
<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>