You are on page 1of 43

JAVASCRIPT NOTES : SIDDHARTH DOSHI

"Use strict"; // treat as JS code as newer version


alert("Hello")//we are using node js, not browser
JS avoid spaces automatically

console.log( 2 + //but this is not good method


3)

Data types

number
bigint -- for long digits
string --> " ",' '
boolean = true/false
null --- standalone value
undefined -- not assigned
symbol -- use in react-- for find unique
object

typeof -- for know type

? null --- type is object

// let score = "undefined"


// console.log(typeof score)
// console.log(typeof(score))

// let valueInNumber = Number(score)


// console.log(typeof valueInNumber)
// console.log(valueInNumber)
// null in number is 0
// undefined in number is NaN
// true/false in number is 1/0
// "abc" in number is NaN

// 1 -- true; 2-- false:in boolean


// ""-- false; "abc"--true:in boolean

// ***********Operations*************

let val = 3
let nagval = -val
console.log(nagval)
// console.log(2+2)
// console.log(2-2)
// console.log(2*2)
// console.log(2**2)
// console.log(2/2)
// console.log(2%2)

console.log("2"+1)
console.log(2+"1")
console.log("1"+2+3)
console.log(2+3+"2")

// console.log(+true)
// console.log(+"")

let gamecounter = 100


// gamecounter++;
++gamecounter
console.log(gamecounter)

let a = null

let b = Number(a)
console.log(b)

// console.log(2>1)
// console.log(2>=1)
// console.log(2<1)
// console.log(2<=1)
// console.log(2==1)
// console.log(2!=1)

// console.log("2" >1)
// console.log("a" > "A")
// console.log(undefined == undefined)

// === yeah data type bhi chech karta hai

// **********Summary************

// Primitive

// 7 types : Stirng, Number, Booleam, null,undefined,BigInt,Symbol

// Refrence , Non primitive


// Array, Objects, Function

// In JS we are not defining datatype during declaretion so it's Dynamic

// for BigInt --- 123n n likho last me

// console.log(typeof b)

const hero = ["shaktiman", "Nagraj"]


let obj= {
name: "hetu",
age: 22,
}

// const f = myfun(){}

// Two types of Memory


// Stack and Heap

// Stack Memory ( Primitive)---- copy


// Heap Memory (Non Primitive)--- give Refrance

let a = "sd"
let b = a
a = "ds"

console.log(b)
console.log(a)

const name = "Raju"


const a = 50

// console.log(name + a) //old method

// // new Method -- string interpolation


// console.log(`Hello my name is ${name} and value of a id $ {a}`)

const gameName = new String('Hello')


// console.log(gameName[0])
// console.log(gameName.__proto__)

// console.log(gameName.length)
// console.log(gameName.toUpperCase())
// console.log(gameName.charAt(2))
console.log(gameName.indexOf('l'))

const as = gameName.substring(0,4)
console.log(as)
// trim() remove spaces in string
// replace('replaced word',' by replacing word')

console.log(gameName.split('-'))

// const balance = 12
// console.log(balance)

// const a = new Number(23)// Object


// console.log(a)

// console.log(balance.toString())
// console.log(balance.toString(16))
// console.log(balance.toFixed(3))

// const a1 = 11121111111
// console.log(a1.toPrecision(1))
// console.log(a1.toExponential())
// console.log(a1.toLocaleString())//US standerd
// console.log(a1.toLocaleString('en-IN'))//INDIAN standerd

// ++++++++++++++++Maths+++++++++++++++

// console.log(Math)

// abs() -- absolute value-- positive value


// round()-- round off value
// ceil--- top value
// floor -- bottom value
// min() and max()

// console.log(Math.random())
// console.log((Math.random()*10) +1)
// console.log(Math.random())

// const min = 10
// const max = 20
// Math.random()*(max-min +1)
// console.log(Math.floor(Math.random()*(max-min +1) ) + min)

// +++++++++++++++ Date and Time++++++++++++

// Date
// let myDate = new Date()
// console.log(myDate)

// console.log(myDate.toDateString())
// console.log(myDate.toISOString())
// console.log(myDate.toLocaleDateString())
// console.log(myDate.toLocaleString())
// console.log(myDate.toLocaleTimeString())
// console.log(myDate.toJSON())
// console.log(myDate.getTimezoneOffset())
// console.log(typeof myDate)

// let myCreatedDate = new Date(2023,0,23)


// console.log(myCreatedDate.toDateString())

// let myCreatedDate1 = new Date(2023,0,23,5,3)


// console.log(myCreatedDate.toLocaleString())

// let myCreatedDate3 = new Date("2023-01-14")


// // console.log(myCreatedDate.toDateString())

// let myTimeStamp = Date.now()


// console.log(myTimeStamp)
// console.log(myCreatedDate3.getTime())
// console.log(Math.floor(Date.now()/1000))

let newDate = new Date()


console.log(newDate)
console.log(newDate.getMonth() + 1)
console.log(newDate.getDate())

// `${newDate.getDay()} and the time`


newDate.toLocaleString('defult',{weekday:"long"})

// arrays

const myArr = [0,1,2,3,4,5]


const arr =[1,"s",'@']
const Arr = new Array(1,2,3)
// Shallow copy hi banati hai isme
// Methods

myArr.push(6)
myArr.pop()
myArr.unshift(0)
myArr.shift()
console.log(myArr.includes(2))
console.log(myArr.indexOf(9))

// .join array ko string bana deta hai


// slice,splice
console.log("A",myArr);

const myn1 = myArr.slice(1,3)


console.log(myn1)
console.log("B ",myArr)

const myn3 = myArr.splice(1,3)


console.log(myn3)
console.log(myArr)

// Splice or slice me kya diffrence?


// Splice Array ko change karta hai par slice nai karta hai

const marvel_hero = ["thor", "loki","hulk"]


const dc = ["superman", "flash", "batman"]
const a = [1,2,3]

// marvel_hero.push(dc)
// console.log(marvel_hero)
// console.log(marvel_hero[3][1])
// const all =marvel_hero.concat(dc).concat(a)
// console.log(all)

// spread method
// const all_new =[...marvel_hero,...dc]
// console.log(all_new)

// flat
const another_array = [1,2,3,[4,5,6],7,[6,7,[2,3,4]]]
const real_another_array = another_array.flat(Infinity)
// yaha infinity ke badle finite depth deni chahiye
console.log(real_another_array )

console.log(Array.isArray("1123"))
console.log(Array.from("1123"))
console.log(Array.from({ name:"1123"}))//interesting

let score1 = 1
let score2 = 2
let score3 = 3
console.log(Array.of(score1,score2,score3))

// object declare methods

//singleton---Always made by constructor never by literals


// Object.create
// Object literals

const JsUsers ={
name:"Sid",
// use [] to use key as Symbol either it will be string

"full name" : "Siddharth",// '.' operator se kabhi access nai kar shakte
age: "18",
// [a]: "Ahmedabad"

}
// key and value in this type of object

// // Object access karne ke methods


// console.log(JsUsers.name)
// console.log(JsUsers["name"])
// // console.log(JsUsers[a])

// Object.freeze(name_of_object)-- value can't change

JsUsers.greeting = function(){
console.log("Hello bro");
}
JsUsers.greeting2 = function(){
console.log(`Hello bro, ${this.name}`);
}

console.log(JsUsers.greeting())
console.log(JsUsers.greeting2())

// singleton

const igUser = new Object()


igUser.username = "sd2003"
igUser.isloggedIn = false

// console.log(igUser)

const regularUser = {
emai : "siddharth@gmail.com",
fullname:{
userkaname:{
firstName:"Sid",
lastName:"Doshi"
}
}
}

// console.log(regularUser.fullname?.userkaname.firstName)

// ? ask for existance of object

const obj1 = {1:"a",2:"b"}

const obj2 = {2:"a",3:"b"}

// const obj3 = {obj1,obj2}


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

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


// console.log(obj3)

const user =[{


id:1,
email:"hello@gmail.com"
},
{
id:1,
email:"hello@gmail.com"
},
{
id:1,
email:"hello@gmail.com"
}]

console.log(user[1].email)
console.log(igUser)
console.log(Object.keys(igUser))
console.log(Object.values(igUser))
console.log(Object.entries(igUser))
console.log(igUser.hasOwnProperty('username'))

const course = {
coursname: "js in hindi",
price:"111"
}

// destructure objects
const{price: p} = course

// console.log(price)
console.log(p)

// APIs

// JSON
// {
// "name" : "Siddharth",
// "countsename": "js ion hindi"
// }

// API array formet


// JSON formater website use to formate data
// [
// {},{}
// ]

// Functions

// defination of function
function sayMyName(){
console.log("Siddharth")
}

// Refrence of function
sayMyName()

// parameter wala function


// parameter is input of function

function addToNumber(n1,n2){
console.log(n1+n2)
}

// when function is called and pass values they are arguments


const a = addToNumber(2,3)
console.log(a)

function addToNumber2(n1,n2){
// method 1 declare karne ke liye
// let result = n1+n2
// return result

// method 2 declare karne ke liye


return n1+n2
// return ke baad kuch bhi likho woh nahi hone wala execute
}

const b = addToNumber2(1,2)
// console.log(b)

function loginmsg(username){
if(username === undefined){
console.log("areh!! naam to do user ko ")
return
}
// or ek tarika
// if(!undefined){
// console.log("areh!! naam to do user ko ")
// return
// }

return `${username} ne abhi log in kiya`


}

console.log(loginmsg("raju"))

console.log(loginmsg())

// rest operator ...- for many parameters input which will be store in array

function calculateCartPrice (...num1){


return num1
}

console.log(calculateCartPrice(2))

// object ---- function

const user = {
username : "Rajesh",
price:199

function handleObj(anyobject){
console.log(`username is ${anyobject.username} and price is
${anyobject.price}`)
}

handleObj(user)
handleObj({username: "kaju", price:200})

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

function returnSecondValue(getArray){

return getArray[1]

console.log(returnSecondValue(myNewArr))

// let a = 20
// var b = 30
// const c = 40

// { } yeah scope hai

// globel scope
if(true){
// block scope
let a = 20
var b = 30
const c = 40
}

// console.log(a)
console.log(b)
// console.log(c)

// var -- muje scope se kuch fark nai padta

// isnpect karke dekhne par globel scope alag hai


// or environment me globel scope alag hai

// nested scope

function one() {
const username = "Siddharth";

function two() {
const website = " youtube";
console.log(username)
}
// console.log(website)
two()
}

// one()

// if(true){
// const username = "Siddharth"
// if( username === "Siddharth"){
// const website = "Youtube"
// console.log(username + website)
// }
// console.log(website)
// }

// console.log(username)

// ++++++++++++ interesting ++++++++++

console.log(addone(5))

function addone(num){

return num +1
}
addone(5)

const addTwo = function(num){


return num +2
}
// only execute after declaretion
console.log(addTwo(5))

// const user = {
// username: " Sid",
// price : 222,
// // this--current context
// welcomeMsg : function(){
// console.log(`${this.username}, welcome to the website`)
// console.log(this)
// }
// }

// user.welcomeMsg()
// user.username = "Sem"
// user.welcomeMsg()
// console.log(this)

// This value--
// Node environment --{}
// Browser --- window(globel object)

// const chai = function chai (){


// let username ="Siddharth"
// console.log(this.username);
// }

// const chai = () =>{


// let username ="Siddharth"
// console.log(this.username);
// }

// chai()

// const addTwo = (n1,n2) => { return n1+n2}

const addTwo = (n1,n2) => (n1+n2)

console.log(addTwo(1,2))

//

// Immediately invoked Function Expression

// function chai(){
// console.log(`DB CONNECTED`)
// }

// chai()

(function chai(){
console.log(`DB CONNECTED`)
})();

// globel scope ke pollution ko hatane ke liye iife ka use hota hai --()()
// ; jaruri hai function ko end karne ke liye
// arrow function bhi use kar shakte ho isme
// Javascript execution context
// 1. {}-- globel ex. context -- > valu of this--window
// 2. functional ex. contect
// 3. eval ex. context

// {}--> memory creation phase


// --> Execution phase

let val1 = 10
let val2 = 5
function addNum(n1,n2){
let total = n1+n2
return total
}

let result1 = addNum(val1,val2)


let result2 = addNum(1,2)

// 1. Globel execution --- > this


// 2. Memory phase
// val1--> undefinded
// val2--> undefinded
// address--> defination
// result1--> undefined
// result2--> undefined

// Execution Phase
// val1-- 10
// val2--5
// addNum ---> New variable environment + execution phase
// 1. ---> Memory Phase
// val1 undefined
// val2 undefined
// total undefined

// 2.---->Execution contact// after finish task it will be delete


// n1 -->10
// n2 -->5
// total--> 15

// New Variable Environment + thread


// 1. ---> Memory Phase
// val1 undefined
// val2 undefined
// total undefined

// 2.---->Execution contact// after finish task it will be delete


// n1 -->1
// n2 -->2
// total--> 3

// Call stack
// in Globel execution -- lifo concept last in first out

// ?? do inspact and open snippits for call stack

// if
// if(condition){

// }

// else if{

// }
// else{

// }

// switch(key){

// case value:
// break;

// default:
// break;

// }

// falsy values
// false,0,-0, BigInt 0n, "", null, undefined,NaN

// truthy values
// "0",'false'," ",[],{},function(){}

// Nullish coalescing operator(??): null undefined

let val1;
val1 = 5 ?? 10
val1 = null ?? 10
val1 = undefined ?? 10
console.log(val1)

// terniary operator
// condition? true :false
// for loop

let array = ["flash", "batman","superman"]

for (let i = 0; i < array.length; i++) {


const element = array[i];
console.log(element)
}

// break and continue

// while loop

while (condition){
// statement
}

// do while loop

do{

}while(condition);

// for of

// for (const iterator of object) {

// }

// ["",""]-- string
// [{},{}]-- objects

// Maps -- no duplicate value-- unique value


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

console.log(map);

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


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

// const myObj ={
// 'game1': 'nfs',
// 'game2':'cfs'
// }

// object is not iterable by for of loop

const myObj ={
'game1': 'nfs',
'game2':'cfs'
}

for (const key in myObj) {


console.log(`${key} is for ${myObj[key]}`);

// for in loop gives key for array


// for in loop not applicable on map
// map itterable nai hai

const coding = ["js","ruby","cpp","java","python","cpp"]

// for each

coding.forEach(function (item,index,array){console.log(item,index, array)})

console.log("----------------");
// arrow function
coding.forEach( item => {
console.log(item)
});

// const coding = ["python","java","cpp","nodejs"]

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


// console.log(item);
// // return item
// })
// // for Each loop koi value return nai karta hai
// console.log(values)

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

const newmn = mn.filter( (num) => num>4 )


// console.log(newmn);

// {} yeah use karoge to return to lagana padegana bhai


// scope open kar rahe ho {} laga kar..!!!!

const newmn1 = mn.filter( (num) => { return num>4} )


// console.log(newmn);

const newnum =[]

mn.forEach(num => {

if(num >4){
mn.push(num)
}
});

// console.log(newmn)

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


// const meranayanum = meranum.map((num)=>{return num+10})

// chain of map and filter


const meranayanum = meranum.map((num)=> num*10).filter((num)=>num>50)
// console.log(meranayanum);

// Reduce
const n = [1,2,3]

const t = n.reduce( function (acc,curval){


console.log(`acc:${acc} and curval:${curval}`);
return acc+curval
},0)

console.log(t)

DOM :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Learning</title>

<style>
.bg-black{
background: rgb(20, 20, 20);
color: white;
}
</style>
</head>
<body class="bg-black">
<div >
<h1 class="heading" id="title">Hello me heading hu <span >test
text</span></h1>
<p>Lorem ipsum dolor sit amet.</p>

<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
</body>

<script src="one.js"></script>
</html>

// According to the one.html

// diagram
// window---> document---> HTML
// HTML---> Head and body
// head--->title and metatags
// title--> textNode
// metatags-->attribute

// Body---->
// div---> attribute (h1 and p are child)
// h1---> textNode and Attribute
// p ---> textNode

// ***************** Write this code in console*********

// document.getElementById('title')

document.getElementById('title').id
document.getElementById('title').className
document.getElementById('title').getAttribute('id')
document.getElementById('title').setAttribute('class','or kuchh naam')
title.style.backgroundColor = 'green'
title.innerText//only visible text content
title.textContent // all content with hodden text (display: none)
title.innerHTML
document.getElementsByClassName('heading')

document.querySelector('h1')
document.querySelectorAll('h1')// for all h1
document.querySelector('.heading')// all selectors select as CSS
const templilist = document.querySelectorAll('li')

// html collection has no for each


// Array.from() this method use to convert ht,l collection in array
// now each loop is aplicable on it

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dom learning</title>
<style>
.bg-black{
background: rgba(0, 0, 0, 0.644);
color: white;
}
</style>
</head>
<body class="bg-black">
<!-- <div > -->
<!-- <h1 id="title" class="heading">Dom learning</h1>
<p>Lorem ipsum dolor sit amet.</p>

<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
</div> -->

<!-- lec 33 -->


<!--
<div class="parent">
<div class="day">Monday</div>
<div class="day">Tuesday</div>
<div class="day">Wednesday</div>
</div> -->

<ul class="language">
<li>Javascript</li>
</ul>
</body>

<script>
// const a= document.querySelector('.parent')
// console.log(a)
// console.log(a.children)
// console.log(a.childNodes);

// const div = document.createElement('div')


// console.log(div);
// div.className = "main"
// div.id = Math.round(Math.random()*10+1)
// div.setAttribute("title","generated title")
// // div.innerText = "Siddharth Doshi"
// div.style.backgroundColor = "green"
// const txt = document.createTextNode("chai aur code")
// div.appendChild(txt)
// document.body.appendChild(div)

//

function addLang(langName){

const li = document.createElement('li');
// li.innerHTML=`${langName}`w,pw
li.appendChild(document.createTextNode(langName))

document.querySelector('.language').appendChild(li)

addLang("Python")

</script>
</html>
DOM
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Learning</title>

<style>
.bg-black{
background: rgb(20, 20, 20);
color: white;
}
</style>
</head>
<body class="bg-black">
<div >
<h1 class="heading" id="title">Hello me heading hu <span >test
text</span></h1>
<p>Lorem ipsum dolor sit amet.</p>

<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
</body>

<script src="one.js"></script>
</html>

// According to the one.html

// diagram
// window---> document---> HTML
// HTML---> Head and body
// head--->title and metatags
// title--> textNode
// metatags-->attribute

// Body---->
// div---> attribute (h1 and p are child)
// h1---> textNode and Attribute
// p ---> textNode
// ***************** Write this code in console*********

// document.getElementById('title')

document.getElementById('title').id
document.getElementById('title').className
document.getElementById('title').getAttribute('id')
document.getElementById('title').setAttribute('class','or kuchh naam')
title.style.backgroundColor = 'green'
title.innerText//only visible text content
title.textContent // all content with hodden text (display: none)
title.innerHTML
document.getElementsByClassName('heading')

document.querySelector('h1')
document.querySelectorAll('h1')// for all h1
document.querySelector('.heading')// all selectors select as CSS
const templilist = document.querySelectorAll('li')

// html collection has no for each


// Array.from() this method use to convert ht,l collection in array
// now each loop is aplicable on it

EVENT

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>htnml Events </title>
</head>
<body style="background-color: #414141; color: aliceblue;">
<h2>Amazing image</h2>
<div >
<ul id="images">
<li><img width="200px" id="photoshop"
src="https://images.pexels.com/photos/3561339/pexels-photo-
3561339.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt="photoshop"></li>
<li><img width="200px" id="japan"
src="https://images.pexels.com/photos/3532553/pexels-photo-
3532553.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt=""></li>
<li><img width="200px" id="river"
src="https://images.pexels.com/photos/3532551/pexels-photo-
3532551.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt=""></li>
<li><img width="200px" id="owl"
src="https://images.pexels.com/photos/3532552/pexels-photo-
3532552.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt="" ></li>
<li><img width="200px" id="prayer"
src="https://images.pexels.com/photos/2522671/pexels-photo-
2522671.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt=""></li>
<li><a style="color: aliceblue;" href="https://google.com"
id="google">Google</a></li>
</ul>
</div>
</body>
<script>
// document.getElementById('owl').onclick = function(){
// alert("owl clicked")
// }

// attachEvent()
// jQuery - on

// type, timestamp, defaultPrevented


// target, toElement, srcElement, currentTarget,
// clientX, clientY, screenX, screenY
// altkey, ctrlkey, shiftkey, keyCode

// 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");
// e.stopPropagation()
// }, false)

// document.getElementById('google').addEventListener('click',function(e){
// e.preventDefault();
// e.stopPropagation()
// console.log("google clicked");
// }, false)

document.querySelector('#images').addEventListener('click', function(e){
console.log(e.target.tagName);
if (e.target.tagName === 'IMG') {
console.log(e.target.id);
let removeIt = e.target.parentNode
removeIt.remove()
}

})

//removeIt.parentNode.removeChild(removeIt)
</script>
</html>

<!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>
<h1>Chai aur code</h1>
<button id="stop">Stop</button>
</body>
<script>
const sayHitesh = function(){
console.log("Hitesh");
}
const changeText = function(){
document.querySelector('h1').innerHTML = "best JS series"
}

const changeMe = setTimeout(changeText, 2000)

document.querySelector('#stop').addEventListener('click', function(){
clearTimeout(changeMe)
console.log("STOPPED")
})
</script>
</html>

<!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>
<h1>Chai aur Javascript</h1>
<button id="start">Start</button>
<button id="stop">Stop</button>
</body>
<script>
const sayDate = function(str){
console.log(str, Date.now());
}

const intervalId = setInterval(sayDate, 1000, "hi")

clearInterval(intervalId)
</script>
</html>

ADVANCE CONCEPT

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" contnt="width=device-width, initial-scale=1.0">
<title>Document</title>

<style>
.bg-black{
background: black;
color: white;
}
</style>
</head>
<body class="bg-black">
<div>
<h1>Lorem ipsum dolor sit amet,
consectetur adipisicing elit.
Eaque, magni.</h1>
</div>
</body>

<script>
const requestUrl = 'https://api.github.com/users/siddharthdoshi06'
console.log(requestUrl);

const xhr = new XMLHttpRequest();


xhr.open('GET',requestUrl);
xhr.onreadystatechange = function(){
console.log(xhr.readyState);

if(xhr.readyState === 4){

// console.log(this.responseText);
const data = JSON.parse(this.responseText);
// URL se jo bhi data aata hai woh object ke badle
// string format me aata hai..!!!
console.table(typeof data)
console.log(data.following)
}
}
xhr.send()

// console.log(xhr.readyState);
</script>
</html>

<!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>
<script>
// Promise

// The Promise object represents the eventual


// completion (or failure) of an asynchronous operation
// and its resulting value.

// 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.

</script>
</body>
</html>
const promise1 = new Promise(function (resolve, reject) {
// Do an async task
// Data Base call, cryptography call, network
// set time out

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

// 2nd syntex

promise1.then(function () {
console.log("Promise consumed");
}); // .then() is connected to resolve

new Promise(function (resolve, reject) {


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

// 3rd

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


setTimeout(function () {
resolve({
name: "Sid",
mail: "sid@hetu.com",
});
}, 1000);
});

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

// 4th

promise4 = new Promise(function (resolve, reject) {


setTimeout(function () {
let error = false;
if (!error) {
resolve({
name: "Sid",
mail: "sid@hetu.com",
});
} else {
reject("ERROR: KUCH TO gadbad hai");
}
}, 1000);
});

const name1 = promise4


.then((user) => {
console.log(user);
return user.name;
})
.then((username) => {
console.log(username);
})
.catch(function (error) {
console.log(error);
}).finally(()=>{
console.log("Promise resolve ya reject ho gaya")
});

// 5th

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


setTimeout(function () {
let error = false;
if (!error) {
resolve({
name: "Sid",
mail: "sid@hetu.com",
});
} else {
reject("ERROR: KUCH TO gadbad hai");
}
}, 1000);

})

// async function consumePromise5() {


// const response = await promise5;
// console.log(response);
// }

// async function consumePromise5() {


// try{
// const response = await promise5
// console.log(response);

// }catch(error){
// console.log(error)
// }
// }

// consumePromise5()

// 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(error)
// }

// }

// getAllUsers()

// lec 41

fetch('https://jsonplaceholder.typicode.com/users')
.then(function(response){
return response.json();
})
.then(function(data){ console.log(data) })
.catch( (error) => console.log("ERROR")
)

// Read about fetch: https://blog.logrocket.com/fetch-api-node-js/


// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

// response = fetch('something like url')


// fetch api yeah do jagah par jaati hai
// 1.-----> 1.data someName, 2. On fullfieldArray[] 3.On Rejection[]
// 2. web browser/Node ---> network request--> yes/no---> at 1.(again)
// now from 1. to globel memory (response: )
const promise1 = new Promise(function (resolve, reject) {
// Do an async task
// Data Base call, cryptography call, network
// set time out

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

// 2nd syntex

promise1.then(function () {
console.log("Promise consumed");
}); // .then() is connected to resolve

new Promise(function (resolve, reject) {


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

// 3rd

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


setTimeout(function () {
resolve({
name: "Sid",
mail: "sid@hetu.com",
});
}, 1000);
});

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

// 4th

promise4 = new Promise(function (resolve, reject) {


setTimeout(function () {
let error = false;
if (!error) {
resolve({
name: "Sid",
mail: "sid@hetu.com",
});
} else {
reject("ERROR: KUCH TO gadbad hai");
}
}, 1000);
});

const name1 = promise4


.then((user) => {
console.log(user);
return user.name;
})
.then((username) => {
console.log(username);
})
.catch(function (error) {
console.log(error);
}).finally(()=>{
console.log("Promise resolve ya reject ho gaya")
});
OOP

# Javascript and classes


# JS prototype based language hai
## Object
-collection of properties and methods
-ex. toLowerCase

## parts of oop
object literal
-Constructor function
-prototype
-Classes
-Instances(new,this)

# 4 pillars
Abstraction
Encapsulation
Inheritance
Polymorphism

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)

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.

*/

const user = {
userName : "Sid",
SignIn: "kiya hai re deva kiya hai",
getUserDetails: function () {
// console.log("Mil gaya re details deva mil gaya re")
// console.log(`User ka naam : ${this.userNmae}`);
console.log(this)
// this ---> current context
}
}

// console.log(user.userNmae);
// // console.log(user.getUserDetails());
// console.log(this)
// // filhaal globel context me kuch nai hai
// // yeah browser me run karoge to bahot kuch milega

// new ---> yeah constructor function hai


// new ek hi object se multiple instance banane ke kaam aata hai

function User(userName){
this.userName = userName

return this
}
// const UserOne= User("Sid")
// const UserTwo= User("Hetu")
// yeha constructor function use nai ho raha
// is liye UserTwo data overwrite kar raha hai
// so use new keyword
// because of new keyword:

// 1.empty instance(object) create


// 2. constructor function called
// 3. this keyword (all arguments) inject
// 4. getting data in function

const UserOne= new User("Sid")


const UserTwo= new User("Hetu")
console.log(UserOne.constructor);
// instance of ke bare me thoda padhna khud se
// console.log(UserOne);

// 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 Sid = new User("Sid", "Sid@hetu.com", 123);


// console.log(Sid.encryptPassword());
// console.log(Sid.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 = function () {
return `${this.username.toUpperCase()}`;
};

const Sid = new User("Sid", "Sid@hetu.com", 123);


console.log(Sid.encryptPassword());
console.log(Sid.changeUsername());

function User(email,password){
this._email = email;
this._password = password;

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

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

const Sid = new User("s@s.com","Sid")


console.log(Sid.email);
console.log(Sid.password);

const User = {
_email : "h@h.com",
_pass : "123",

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


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

get pass(){return this._pass.toUpperCase()},


set pass(value){this._pass = value}
}

const Sid = Object.create(User)


console.log(Sid.email);

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

logMe(){
console.log(`USERNAME is ${this.username}`)
}
}

class Teacher extends User{


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

addCourse (){
console.log("New course added by sir");
}
}

const Sid = new Teacher("Sid","Sid@hetu.com",123)


console.log(Sid);

const Hetu = new User("Hetu")


Hetu.logMe("Sid@Hetu.com")
console.log(Hetu);

console.log(Sid === Hetu)

console.log(Sid instanceof User);


STATIC KEYWORD

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

logMe(){
console.log(`USERNAME is ${this.username}`)
}

static createId(){
return '123'
}
}

class Teacher extends User{


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

const Sid = new User("Sid")


console.log(Sid.createId())

// static karne ke baad inherit karne par


// bhi woh function child ko nahi milta hai

CALL AND THIS

// Call and this

function Setusername(username){
// complex db call
this.username = username;
}
function createUser(username,email,password){
Setusername.call(this, username)
this.email = email,
this.password = password

const sid = new createUser("sid","Sid@Hetu.com",123)


console.log(sid);

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:3000"

// Requirement
document
.querySelector('button')
.addEventListener('click',this.handleClick.bind(this))

}
handleClick(){
console.log("Button click");
console.log(this.server);
console.log(this);

}
}

const app = new React()


</script>
</html>
GETOWNPROPERTYDESCRIPTOR OBJECT
const discriptor = Object.getOwnPropertyDescriptor(Math, "PI")
console.log(discriptor)
console.log(Math.PI);
Math.PI = 5
console.log(Math.PI)

const Sid = {
name:'Siddharth',
Age: 45,
isAlive: true
}
console.log(Sid);
console.log(Object.getOwnPropertyDescriptor(Sid,"name"));

Object.defineProperty(Sid,"name",{
writable:false,
enumerable:false,
configurable:false

})

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

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


if (typeof value != 'function') {
console.log(`${key} : ${value}`);
}
}

FUN WITH JS : CLOSER CONCEPT


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Closer</title>
</head>
<body>

<button id="orange">
Orange
</button>

<button id="green">
Green
</button>

<script>

// function init(){
// let name = "Siddharth";
// function displayName(){
// console.log(name)
// }
// displayName();
// }

// init()

// Concept of closer

// perent function me declare variable child function


// access kar shakte hai par child ki property parent function
// or dusra child nahi access kar shakta
// secret ke example se samjaya gaya hai

// function outer(){
// let username ="Sid"
// console.log(secret);
// function inner(){
// let secret ="123"
// console.log(username);
// }
// inner()

// function inner2(){
// console.log(username);
// console.log(secret)
// }
// inner2()
// }

// outer()
// console.log(username)

// function makeFunc(){
// const name ="Sid"
// function displayName(){
// console.log(name);
// }
// return displayName
// }

// const myFunc = makeFunc();


// myFunc();

// 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>

</body>
</html>

You might also like