// JAVASCRIPT
// ❓What is javascript
// 👉 A high level, single threaded, garbage collected interpreted or just in time
// complied Prototyped based , multi-paradigm dynamic language with a non-blocking
// event loop, made famous to build websites , it was created in 1995 in just one
// week by BRENDAN EICH
// ❓ What is high level language ?
// 👉 A computer programming language that resembles natural language or mathematical
// notation and is designed to reflect the requirements of a problem
// ❓ What is single-thread ?
// 👉 A single-thread language is one with a single call stack and a single memory heap.
// It means that it runs only one thing at a time.
// ❓ What is garbage collector ?
// 👉 Some high-level languages, such as JavaScript, utilize a form of automatic memory
// management known as garbage collection (GC). The purpose of a garbage collector is
// to monitor memory allocation and determine when a block of allocated memory is no
// longer needed and reclaim it.
// ❓ What is just in time complier ?
// 👉 The Just-In-Time (JIT) compiler is a component of the runtime environment that
// improves the performance
// ❓ What is Prototyped based ?
// 👉 Prototype-based programming is a style of object-oriented programming in which
// classes are not explicitly defined, but rather derived by adding properties and
// methods to an instance of another class or, less frequently, adding them to an
// empty object.
// ❓ What is multi-paradigm dynamic language ?
// 👉 multi-paradigm language. a programming language that supports both procedural and
// object-oriented programming philosophies.
// ❓ What is procedural programming language ?
// 👉 A procedural language is a type of computer programming language that specifies a
// series of well-structured steps and procedures within its programming context to
// compose a program
// ❓ What is non blocking
// 👉 It refers to the program that does not block the execution of further operations.
// Non-Blocking methods are executed asynchronously. Asynchronously means that the
// program may not necessarily execute line by line
// 🌟 PRINT 🌟
console.log("HELLO WORLD");
// 🌟 VARIABLES 🌟
// ❓ What is variable
// 👉 Variable means anything that can vary. In JavaScript,
// a variable stores the data value that can be changed later on.
// Use the reserved keyword var to declare a variable in JavaScript.
// variable can store some information
// we can use that information later
// we can change that information later
// declare a variable
var firstName = "Himanshu";
// use a variable
console.log(firstName);
// change value
firstName = "MONU"
// again use variable
console.log(firstName);
// 🌟 RULES FOR NAMING VARIABLES 🌟
// you cannot start with number
// example :-
// 1value (invalid)
// value1 (valid)
// you can use only undersore _ or dollar symbol
// first_name (valid)
// _firstname (valid)
// first$name (valid)
// $firstname (valid)
// you cannot use spaces
// var first_name = "harshit"; // snake case writing
// var firstName = "harshit"; // camel case writing
// first name (invalid)
// convention
// start with small letter and use camelCase
// 🌟🌟 let keyword 🌟🌟
// ❓ What is let keyword
// 👉 let allows you to declare variables that are limited to the scope of a
// block statement, or expression on which it is used, unlike the var keyword,
// which declares a variable globally, or locally to an entire function
// regardless of block scope
// block scope vs funtion scope (covered later)
// 🌟🌟 const 🌟🌟
// ❓ What is const keyword
//👉 Constants are block-scoped, much like variables declared
// using the let keyword. The value of a constant can't be
// changed through reassignment
// declare constants
const pi = 3.14;
console.log(pi);
// 🌟 STRING INDEXING 🌟
let firstName = "harshitdfjakldsfdf";
// h a r s h i t
// 0 1 2 3 4 5 6
// console.log(firstName[0]);
// length of string
// firstName.length
console.log(firstName.length);
console.log(firstName[firstName.length-2]);
// last Index : length - 1
// 🌟🌟 Useful string method() 🌟🌟
// 👉 Strings are immutable
// ❓ What is immutable ?
// 👉 Immutables are the objects whose state cannot be changed once the object
// is created. Strings and Numbers are Immutable.
// 👉 trim()
// ➡️ trim() The trim() method removes whitespace
// from both ends of a string and returns a new string,
// without modifying the original string.
// 👉 toUpperCase()
// ➡️ The toUpperCase() method returns the value of the string
// converted to uppercase. This method does not affect the
// value of the string itself.
// 👉 toLowerCase()
// ➡️ The toLowerCase() method returns the value of the string
// converted to lowercase. This method does not affect the
// value of the string itself.
// 👉 slice()
// ➡️ The slice() method returns selected elements in an array,
// as a new array. The slice() method selects from a given start,
// up to a (not inclusive) given end. The slice() method does not
// change the original array.
// 🛑 many more string methods out there
let firstName = "Himanshu Tiwari";
// 👉 trim()
console.log(firstName.trim());
// 👉 toUpperCase()
console.log(firstName.toUpperCase());
// 👉 toLowerCase()
console.log(firstName.toLowerCase());
// 👉 slice()
// slice() extrats a part of a string and returns the extracted part
// in a new string.
let newString = firstName.slice(3,firstName.length)
console.log(newString);
// 🌟 typeof operator 🌟
// ❓ what is typeof operator
// 👉 In JavaScript, the typeof operator returns the
// data type of its operand in the form of a string.
// let age = 22;
// let firstName = "harshit";
// console.log(typeof age);
// // 22 -> "22"
// // convert number to string.
// age = age + "";
// console.log(typeof(age)); "22"
// // convert string to number.
// let myStr = +"34";
// console.log(typeof myStr);
let age = "ram";
age = Number(age);
console.log(age);
console.log(typeof age);
// 🌟🌟 Data types 🌟🌟
// ❓ What is Data types
// 👉 A data type, in programming, is a classification that specifies
// which type of value a variable has and what type of mathematical,
// relational or logical operations can be applied to it
// 👉 there are two types of data types
// 1️⃣ primitive data types
// 2️⃣ non-primitive data types
// 1️⃣ primitive data types
// 👉 In JavaScript, a primitive (primitive value, primitive data type)
// is data that is not an object and has no methods.
// ➡️ There are 7 primitive data types in javascript
// 👉 string
// 👉 number
// 👉 booleans
// 👉 undefined
// 👉 null
// 👉 BigInt
// 👉 Symbol
// ➡️ There are 3 reference data types in javascipt
// 👉 Array []
// 👉 function ()
// 👉 Object {}
// string concatenation
let string1 = "17";
let string2 = "10";
let newStringg = +string1 + +string2;
console.log(typeof newStringg);
// template string
let myAge = 22;
let firstName = "harshit"
// "my name is harshit and my age is 22 "
// let aboutMe = "my name is " + firstName + " and my age is " + age;
let aboutMe = `my name is ${firstName} and my age is ${myAge}`
console.log(aboutMe);
// 🌟 🌟
// 🌟 undefined 🌟
// ❓ What is undefined ?
// 👉 A variable that has not been assigned a value is of type undefined
// 🌟 null 🌟
// ❓ What is null ?
// 👉 In JavaScript, null is a special value that represents an empty or unknown value.
// let firstName;
// console.log(typeof firstName);
// firstName = "Harshit";
// console.log(typeof firstName, firstName);
// let myVariable = null;
// console.log(myVariable);
// myVariable = "harshit";
// console.log(myVariable, typeof myVariable);
// console.log(typeof null);
// bug , error
// BigInt
// let myNumber = BigInt(12);
// let sameMyNumber = 123n;
// // console.log(myNumber);
// // console.log(Number.MAX_SAFE_INTEGER);
// console.log(myNumber+ sameMyNumber);
// 🌟 booleans & comparison operator 🌟
// booleans
// true, false
// let num1 = 7;
// let num2 = "7";
// console.log(num1<num2);
// == vs ===
// console.log(num1 === num2);
// != vs !==
// console.log(num1 !== num2);
// ❓ what is difference between == and === ?
// 👉 == in JavaScript is used for comparing two variables,but it ignores the datatype
// of variable.=== is used for comparing two variables but this operator also checks
// datatype and compares two values.
// 🌟🌟 if else condition 🌟🌟
// ❓ what is conditional statement?
// 👉 The conditional statement executes a block of code if a specified condition
// is true. If the condition is false, another block of code can be executed.
// let age = 17;
// if(age>=18){
// console.log("User can play ddlc");
// }else {
// console.log("User can play mario");
// }
// let num = 13;
// if(num%2===0){
// console.log("even");
// }else{
// console.log("odd");
// }
// 🌟🌟 truthy and falsy values 🌟🌟
// ❓ What is truthy and falsy values
// 👉 In JavaScript, a truthy value is a value that is considered
// true when encountered in a Boolean context. All values are
// truthy unless they are defined as falsy. That is, all values
// are truthy except false ,0,-0,0n,"",null,undefined, and NaN.
// JavaScript uses type coercion in Boolean contexts.
// 1️⃣ falsy value
// 👉 false
// 👉 ""
// 👉 null
// 👉 undefined
// 👉 0
// 2️⃣ truthy values
// 👉 "abc"
// 👉 1, -1
// let firstName= 0;
// if(firstName){
// console.log(firstName);
// }else{
// console.log("firstName is kinda empty");
// }
// 🌟 Ternary operator 🌟
// let age = 4;
// let drink;
// if(age>=5){
// drink = "coffee";
// }else{
// drink = "milk";
// }
// console.log(drink);
// ternary operator / conditional operator
// let age = 3;
// let drink = age >= 5 ? "coffee" : "milk";
// console.log(drink);
// 🌟🌟 && and || operator 🌟🌟
// ❓ What is && operator?
// 👉 it check if your both argument need to be true
// ❓ What is || operator ?
// 👉 it run if only one argument is true
// if(firstName[0] === "H"){
// console.log("your name starts with H")
// }
// if(age > 18){
// console.log("you are above 18");
// }
// if(firstName[0] === "H" && age>18){
// console.log("Name starts with H and above 18");
// }else{
// console.log("inside else");
// }
let firstName = "arshit";
let my_age = 16;
if(firstName[0] === "H" || my_age>18){
console.log("inside if");
}else{
console.log("inside else");
}
// 🌟 nested if else 🌟
// winning number 19
// 19 your guess is right
// 17 too low
// 20 too high
let winningNumber = 19;
let userGuess = +prompt("Guess a number");
if(userGuess === winningNumber){
console.log("Your guess is right!!");
}else{
if(userGuess < winningNumber){
console.log("too low !!!");
}else{
console.log("too high !!!");
}
}
// if
// else if
// else if
// else if
// else
// let tempInDegree = 50;
// if(tempInDegree < 0){
// console.log("extremely cold outside");
// }else if(tempInDegree < 16){
// console.log("It is cold outside");
// }else if(tempInDegree < 25){
// console.log("wheather is okay ");
// }else if(tempInDegree < 35){
// console.log("lets go for swim");
// }else if(tempInDegree < 45){
// console.log("turn on AC");
// }else{
// console.log("too hot!!");
// }
// console.log("hello");
// let tempInDegree = 50;
// if(tempInDegree < 0){
// console.log("extremely cold outside");
// }else if(tempInDegree < 16){
// console.log("It is cold outside");
// }else if(tempInDegree < 25){
// console.log("wheather is okay ");
// }else if(tempInDegree < 35){
// console.log("lets go for swim");
// }else if(tempInDegree < 45){
// console.log("turn on AC");
// }else{
// console.log("too hot!!");
// }
// console.log("hello there");
let tempInDegree = 4;
if(tempInDegree > 40){
console.log("too hot");
}else if(tempInDegree > 30){
console.log("lets go for swim");
}else if(tempInDegree > 20){
console.log("weather is cool");
}else if(tempInDegree > 10){
console.log("it is very cold outside");
}else{
console.log("extremely cold");
}
console.log("hello");
// 🌟🌟 switch statement 🌟🌟
// ❓ What is switch statement?
// 👉 The switch statement evaluates an expression, matching the expression's
// value to a case clause, and executes statements associated with that case,
// as well as statements in case s that follow the matching case
// let day = 7;
// if(day === 0){
// console.log("Sunday");
// }else if(day ===1){
// console.log("Monday");
// }else if(day ===2){
// console.log("Tuesday");
// }else if(day ===3){
// console.log("Wednesday");
// }else if(day ===4){
// console.log("Thrusday");
// }else if(day ===5){
// console.log("Friday");
// }else if(day ===6){
// console.log("Saturday");
// }else{
// console.log("Invalid Day");
// }
let day = 9;
switch(day){
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thrusday");
break;
case 5:
console.log("Friday");
break;
case 6:
console.log("Saturday");
break;
default:
console.log("Invalid Day");
}
// 🌟🌟 LOOPS 🌟
// 👉 Loops are used in JavaScript to perform repeated tasks based on a condition
// 🌟 while loop
// 0 se 9
// dry don't repeat yourself
let j = 0; // 1 2 3 4
while(i<=9){
console.log(j);
i++;
}
console.log(`current value of i is ${i}`);
console.log("hello");
// while loop example
let num = 100;
// let total = 0; //1 + 2 +3
// let i = 0;
// while(i<=100){
// total = total + i;
// i++;
// }
// console.log(total);
// let total = (num*(num+1))/2;
// console.log(total);
// 🌟 for loop 🌟
// print 0 to 9
// for(let i = 0;i<=9;i++){
// console.log(i);
// }
// console.log("value of i is ",i);
// sum of first 10 natural number using for loop
// let total = 0;
// for (let i = 0; i <= 100; i++){
// total = total + i
// }
// console.log(total);
// break and continue
for (let i = 0; i <= 10; i++){
if(i===5){
break;
}
console.log(i);
}
// 🌟 Do while loop 🌟
let i = 10;
do{
console.log(i);
i++
}while(i<=9)
// 🌟🌟 ARRAY 🌟🌟
// 👉 An array is an object that can store multiple values at once.
// reference type
// how to create arrays
// ordered collection of items
// let fruits = ["apple", "mango", "grapes"];
// let numbers = [1,2,3,4];
// let mixed = [1,2,2.3, "string", null, undefined];
// console.log(mixed);
// console.log(numbers);
// console.log(fruits[2]);
// let fruits = ["apple", "mango", "grapes"];
// let obj = {}; // object literal
// // console.log(fruits);
// // fruits[1] = "banana";
// // console.log(fruits);
// console.log(typeof fruits);
// console.log(typeof obj);
// console.log(Array.isArray(fruits));
// console.log(Array.isArray(obj));
// array push pop
// array shift unshift
let fruits = ["apple", "mango", "grapes"];
console.log(fruits);
// 👉 push
// The push() method adds one or more element to the
// end of an array and return the new length of the array.
// fruits.push("banana");
// console.log(fruits);
// 👉 pop
// The pop() method removes the last element from an array and return
// that element. This method changes the length of the array.
// let poppedFruit = fruits.pop();
// console.log(fruits);
// console.log("popped fruits is", poppedFruit);
// 👉 unshift
// The unshift() method adds one or more elements to the
// begining of an array and return the new length of the array.
// fruits.unshift("banana");
// fruits.unshift("myfruit");
// console.log(fruits);
// 👉 shift
// The shift() method removes the first element from an array and
// returns that removes element. This method changes the length of the
// array.
// let removedFruit = fruits.shift();
// console.log(fruits);
// console.log("removed fruits is ", removedFruit);
// 🌟 primitve vs reference data types 🌟
// let num1 = 6;
// let num2 = num1;
// console.log("value is num1 is", num1);
// console.log("value is num2 is", num2);
// num1++;
// console.log("after incrementing num1")
// console.log("value is num1 is", num1);
// console.log("value is num2 is", num2);
// reference types
// array
let array1 = ["item1", "item2"];
let array2 = array1;
console.log("array1", array1);
console.log("array2", array2);
array1.push("item3");
console.log("after pushing element to array 1");
console.log("array1", array1);
console.log("array2", array2);
// 🌟 how to clone array 🌟
// how to concatenate two arrays
let array1 = ["item1", "item2"];
// let array2 = ["item1", "item2"];
// let array2 = array1.slice(0).concat(["item3", "item4"]);
// let array2 = [].concat(array1,["item3", "item4"]);
// new way
// spread operator
let oneMoreArray = ["item3", "item4"]
let array2 = [...array1, ...oneMoreArray];
array1.push("item3");
console.log(array1===array2);
console.log(array1)
console.log(array2)
// 🌟 for loop in array 🌟
let fruitss = ["apple", "mango", "grapes", "banana"];
// for(let i=0; i<=9;i++){
// console.log(i);
// }
// console.log(fruits.length);
// console.log(fruits[fruits.length-2]);
let fruits2 = [];
for(let i=0; i < fruits.length; i++){
fruits2.push(fruits[i].toUpperCase());
}
console.log(fruits2);
// 🌟 while loop in array 🌟
const fruits = ['apple','mango','grapes'];
let i = 0;
while(i<fruits.length){
console.log(fruits[i]);
i++;
}
// 🌟 For of loop 🌟
// for of loop gives us the value
const fruits = ["Papaya","orange",'apple','mango','grapes'];
for (let fruit of fruits){
console.log(fruit);
}
// 🌟 for in loop 🌟
// for in loop gives us the index
// for in loop kisi bhi object ki key lene ke liye use karte hain
// ya index lene ke liye use karte hain
// for of loop kisi v literable ko iterate karne ke liye use karte hain
const fruits = ['apple','mango','papaya'];
const fruits2 = [];
for(let index in fruits){
fruits2.push(fruits[index]);
}
console.log(fruits2);
// 🌟 ARRAY DISTRUCTURING 🌟
const myArray = ["Rohan" , "Sohan" , "Mohan", "Johan"];
// let myVar1 = myArray[0]
// let myVar2 = myArray[1]
// let myVar3 = myArray[2]
// console.log("The value of first var = " + myVar1);
// console.log("The value of second var = " + myVar2);
// Now we have easy trick to do the same thing.
// let [myVar1, myVar2, myVar3] = myArray;
// console.log("The value of first var = " + myVar1);
// console.log("The value of second var = " + myVar2);
// we can skip the index by using commas.
// for ex.
// let [myVar1, ,myVar2] = myArray;
// console.log("The value of first var = " + myVar1);
// console.log("The value of second var = " + myVar2);
// const myBioData = ['himanshu','kumar',19];
// 🌟🌟 OBJECT 🌟🌟
// 👉 In JavaScript, an object is a standalone entity, with properties and type.
// JavaScript objects can have properties, which define their characteristics
// // objects reference type
// // arrays are good but not sufficient
// // for real world data
// // objects store key value pairs
// // objects don't have index
// // 🌟 how to create objects 🌟
// const person = {
// name : "Himanshu",
// // we can write our keys in string
// "age" : 19,
// class : 12,
// hobbies : ["cricket","singing","games"]
// }
// console.log(person);
// // 🌟 How to access data from object 🌟
// // we can access object data by using dot(.) sign
// console.log(person.name)
// console.log(person.age)
// // we can access our key using string sign , without string sign give error
// console.log(person["class"]);
// console.log(person.hobbies[1])
// // 🌟 How to add key value pair to object 🌟
// person.gender = "male"
// console.log(person);
// // 🌟 Difference between dot and bracket notation 🌟
// // 1st ex :-
// // const person2 = {
// // name : "Roahn",
// // age : 22,
// // "person hobbies" : ['games','sleeping']
// // }
// // this will show error , we cant access with dot notation when there's space
// // console.log(person2.person hobbies);
// // We can access it through bracket notation
// // console.log(person2["person hobbies"]);
// // 2nd ex :-
// const key = 'email'
// const person2 = {
// name : "Roahn",
// age : 22,
// "person hobbies" : ['games','sleeping']
// }
// person2[key] = "abc@gamail.com"
// console.log(person2);
// 🌟 How to iterate object 🌟
// const person3 = {
// name : "mohan",
// age : 28,
// hobbies : ['dancing','singing']
// }
// there are two methods to itrerate through arrays
// 1. for in loop
// 2. Object.keys
// for (let key in person3){
// console.log(`${key} : ${person3[key]}`);
// }
// console.log(Object.keys(person3));
// for(let key of Object.keys(person3)){
// console.log(person3[key]);
// }
// ❓Question
const key1 = "objkey1";
const key2 = "objkey2";
const value1 = "myvalue1";
const value2 = "myvalue2";
// const obj = {
// objkey1 : "myvalue1",
// objkey2 : "myvalue2"
// }
// 1st method :-
// const obj = {
// [key1] : value1,
// [key2] : value2
// }
// console.log(obj);
// 2nd method
const obj = {}
obj[key1] = value1;
obj[key2] = value2;
console.log(obj);
// 🌟 Spread Operator (clone) 🌟
// This is how we use spread operator in arrays
// let array = ["mango","apple","banana"];
// let newArr = [...array, "papaya",'gauva','grapes']
// console.log(newArr);
// how to use spread operator in objects
let obj = {
key1 : "value1",
key2 : "value 2"
}
let newObj = {
name : "ram",
class : 4,
...obj
}
console.log(obj);
console.log(newObj);
// 🌟 Object destructuring🌟
// 👉 ham object destructuring values ko
// alag veriables me store karne ke liye use kate hain
const band = {
bandName : "one direction",
famousSong : "Story of my life",
leader : "harry styles",
member : 5
}
// const bandName = band.bandName
// const famousSong = band.famousSong
// console.log(bandName , famousSong);
// now Object destructuring
const {bandName:var1 , famousSong:var2 , ...restProperties} = band;
// here var1 and var2 are variable , we can change
// console.log(bandName);
// console.log(bandSong);
console.log(var1);
console.log(var2);
console.log(restProperties); // rest unused properties will show in here
// 🌟 object inside array 🌟
// very useful in real world applications
const users = [
{ userId : 1 , firstName : "Rohit" , gender : "Male" },
{ userId : 2 , firstName : "Mohit" , gender : "Male" },
{ userId : 3 , firstName : "Sohit" , gender : "Male" },
]
for (let user of users){
console.log(user.firstName);
}
// 🌟 Nested distructuring 🌟
const users = [
{ userId : 1 , firstName : "Rohit" , gender : "Male" },
{ userId : 2 , firstName : "Mohit" , gender : "Male" },
{ userId : 3 , firstName : "Sohit" , gender : "Male" },
]
const [{firstName:FN}, ,{gender:G}]=users;
// here FN and G is varabile created by me
console.log(FN);
console.log(G);
// 🌟🌟🌟 FUNCTIONS 🌟🌟🌟
function sayHello() {
console.log("Hello!");
}
sayHello()
function sumTwoNumbers(a, b) {
return a + b
}
const returnedValue = sumTwoNumbers(2, 2);
console.log(returnedValue);
// here a and b is parameters and 2,2 is arguments
// ❓ Question
// isEven
// input : 1 number
// output : true,false
function isEven(a) {
if (a % 2 == 0) {
return true
}
return false
}
isEven(10);
// ❓Question
// firstChar
// input : anystring
// output : first character
function firstChar(string) {
return string[0];
}
const firstCharOutput = firstChar("RAMU");
console.log(firstCharOutput);
// ❓Question
// function : findTarget
// input : array , target(number)
// output :index of target if target is present in array otherwise -1
let myArr = [12, 5, 68, 4, 58,]
function findTarget(arr, presentNum) {
for (let i = 0; i <= arr.length; i++) {
if (arr[i] === presentNum) {
return i
}
}
return -1
}
let answer = findTarget(myArr, 58);
console.log(answer);
// 🌟Funciton expression🌟
// eg
const addTwoNumbers = function (a, b) {
return a + b;
}
console.log(addTwoNumbers(3, 4));
const singHappyBirthday = function (name) {
console.log(`Happy Birthday to you ${name}`);
}
singHappyBirthday("Priyanshu")
// 🌟Arrow functions🌟
const sayMyName = (name) => {
console.log(`My name is ${name}`);
}
sayMyName("himanshu")
const myName = (name) => name;
const newName = myName("Himanshu");
console.log(newName);
// 🌟Function Inside function🌟
const func1 = () => {
const func2 = () => {
console.log("inside func2");
}
const addTwoNumbers = (num1,num2) => {
return num1 + num2;
}
const mulNum = (a,b) => a*b
console.log("inside func1");
func2();
console.log(addTwoNumbers(1,2));
console.log(mulNum(3,5));
}
func1() // only func2 will print now
// 🌟Lexical scope🌟
const myVar = "value1";
function myApp() {
function myFunc() {
// const myVar = "value2" , it will check the myVar
// if it cant find here then it go on top
const myFunc2 = () => {
console.log("inside myFunc",myVar);
}
myFunc2()
}
console.log(myVar);
myFunc()
}
myApp()
// 🌟BLOCK SCOPE VS FUNCTION SCOPE🌟
// 🌟 let and const are block scope
// ---> we cant use block outside of the block
// 🌟 var is function scope
// ---> we can use function scope outside of the block
// This is how blocks look like {}
{
let emoji = "🤔";
console.log(emoji);
const emoji2 = "👋🏼"
console.log(emoji2);
}
{
let emoji = "😆"
console.log(emoji);
const emoji2 = "😅"
console.log(emoji2);
}
// we can use var anywhere :-
{
var message = "Hey MOM !"
}
{
console.log(message);
}
// 🌟Default Parameters🌟
function addTwoNumbers(a,b=6) {
return a+b
}
console.log(addTwoNumbers(5));
// 🌟Rest parameter🌟
// function myFunc(a,b,...c) {
// console.log(`a is ${a}`)
// console.log(`b is ${b}`)
// console.log(`c is ${c}`)
// }
// myFunc(1,2,3,4,5,6,7)
// ❓Question
// addAll (1,2,5,85,74,5)
// function addAll(...numbers) {
// let total = 0;
// for (let number of numbers){
// total = total + number
// }
// return total;
// }
// const ans = addAll(1,2,3);
// console.log(ans);
// ❓ add 1,2,3 using foor loop
function addNum(...myArgs){
let result = 0;
for (let i = 0; i < myArgs.length; i++){
result = result + myArgs[i]
}
console.log(result);
}
addNum(1,2,3)
// 🌟 Parameter destructing 🌟
// we use it with Object , react
const person = {
name : "ABC",
gender : "Male"
}
function printDetails ({name,gender,age}){
console.log(name);
console.log(gender);
console.log(age); // undefined
}
printDetails(person)
// 🌟 HIGHER ORDER FUNCTION 🌟
// 🌟 Callback function 🌟
function myFunc2(name){
console.log("inside my func 2")
console.log(`your name is ${name}`);
}
function myFunc(callback){
console.log("hello there I am a func and I can..")
callback("harshit");
}
myFunc(myFunc2);
// 🌟Function returning function🌟
function myFunc(){
function hello(){
return "hello world"
}
return hello;
}
const ans = myFunc();
console.log(ans());
// 🌟IMPORTANT ARRAY METHODS🌟
// 🌟 forEach()
// 🌟 map()
// 🌟 filter()
// 🌟 reduce()
// 👉 forEach
// we can't return in foreach
// it doenn't return array in return
let numbers = [1,2,3,4,5];
numbers.forEach(function (element,index,array){
console.log(`Elements are :- ${element} Index are :- ${index}`);
})
// we can make function outside too
function myFunc (num , index){
console.log(`number is ${num} and the index is ${index}`);
}
numbers.forEach(myFunc)
// 👉 map
// it always create new array
// always use return in map function otherwise it shows undefined
const numbers2 = [3,4,6,8];
let squareRoot = numbers2.map((n)=>{
return n+n;
})
console.log(squareRoot);
// // we can make function outside too
function myNum (number,index){
return number + number;
}
const ans = numbers2.map(myNum);
console.log(ans);
// 👉 filter
// it help us to filter the array
const numbers3 = [1,2,3,4,5,6,7,8,9,10];
let isEven = numbers3.filter((number)=>{
return number % 2 === 0;
})
console.log(isEven);
// 👉 reduce
const numbers4 = [1,2,3,4,5, 10];
// aim : sum of all the numbers in array
const sum = numbers4.reduce((accumulator, currentValue)=>{
return accumulator + currentValue;
}, 100); // 100 is initial value // current value 1
console.log(sum);
// accumulator , currentValue, return
// 1 2 3
// 3 3 6
// 6 4 10
// 10 5 15
// 15 10 25
const userCart = [
{productId: 1, productName: "mobile", price: 12000},
{productId: 2, productName: "laptop", price: 22000},
{productId: 3, productName: "tv", price: 15000},
]
const totalAmount = userCart.reduce((totalPrice, currentProduct)=>{
return totalPrice + currentProduct.price;
}, 0) // 0 is initial value
console.log(totalAmount);
// total price currentValue return
// 0 {} 12000
// 12000 22000 34000
// 34000 15000 49000
// 👉 sort method
// ASCII TABLE
//char : ascii value
// '0' : 48
// '1' : 49
// '2' : 50
// '3' : 51
// '4' : 52
// '5' : 53
// '6' : 54
// '7' : 55
// '8' : 56
// '9' : 57
// ':' : 58
// ';' : 59
// '<' : 60
// '=' : 61
// '>' : 62
// '?' : 63
// '@' : 64
// 'A' : 65
// 'B' : 66
// 'C' : 67
// 'D' : 68
// 'E' : 69
// 'F' : 70
// 'G' : 71
// 'H' : 72
// 'I' : 73
// 'J' : 74
// 'K' : 75
// 'L' : 76
// 'M' : 77
// 'N' : 78
// 'O' : 79
// 'P' : 80
// 'Q' : 81
// 'R' : 82
// 'S' : 83
// 'T' : 84
// 'U' : 85
// 'V' : 86
// 'W' : 87
// 'X' : 88
// 'Y' : 89
// 'Z' : 90
// '[' : 91
// '\' : 92
// ']' : 93
// '^' : 94
// '_' : 95
// '`' : 96
// 'a' : 97
// 'b' : 98
// 'c' : 99
// 'd' : 100
// 'e' : 101
// 'f' : 102
// 'g' : 103
// 'h' : 104
// 'i' : 105
// 'j' : 106
// 'k' : 107
// 'l' : 108
// 'm' : 109
// 'n' : 110
// 'o' : 111
// 'p' : 112
// 'q' : 113
// 'r' : 114
// 's' : 115
// 't' : 116
// 'u' : 117
// 'v' : 118
// 'w' : 119
// 'x' : 120
// 'y' : 121
// 'z' : 122
// '{' : 123
// '|' : 124
// '}' : 125
// sort method change the original array
// it can take callback function
const numbers = [5,7,2,1,0,4,1200];
numbers.sort();
console.log(numbers);
// output
// [0, 1, 1200, 2, 4, 5, 7]
// 👉 This is because javascript change these numbers in string and then compare
// by ascii values . ascii table is given on top
// now how javascript do it
//[0, 1, 1200, 2, 4, 5, 7]
// JS check the string's first number and compare in ascii table
// '0' : 48
// '1' : 49
// '2' : 50
// '3' : 51
// '4' : 52
// '5' : 53
// '6' : 54
// '7' : 55
// '8' : 56
// '9' : 57
// [0, 1, 1200, 2, 4, 5, 7]
// [48,49,49,,40,50,52,,52,55]
// 👉 here javascript see 1200 as a string and only take first character/number
// which is '1' and compare in ascii table.
// 👉 There is a benifit of this in alphabetical sorting
let userName = ["Mohan","Sohan","Johan","Rohan","ankit"];
let sortedName = userName.sort();
console.log(sortedName);
// 🛑 Note :- Capital letter will always come at first
//👉 How to deal with numbers
const number2 = [7,5,2,9,1,0,410,1200];
numbers.sort((a,b)=>{
return a-b
// 👉 a-b ----> assending
// 👉 b-a ----> desending
});
console.log(number2);
// 👉 No need to know how it works
// 1200,410
// a-b ---> 790
// a-b ---> postive (greater than 0) ---> b, a
// 410 , 1200
// a-b ---> negative ----> a,b
// 5, 9 ---> -4
// shoping application example :-
const producsts = [
{ productId : 1, productName : "p1" , price : 400 },
{ productId : 2, productName : "p2" , price : 3000 },
{ productId : 3, productName : "p3" , price : 60 },
{ productId : 4, productName : "p4" , price : 10000 }
]
// Low To High
const lowToHigh = producsts.sort((a,b)=>{
return a.price-b.price;
})
console.log(lowToHigh);
// 👉 find method
const myArray = ["Hello","cat","dog","lion"];
const lenght3 = myArray.find((string)=>string.length===3);
console.log(lenght3);
// realistic example
const users = [
{userId : 1, userName : "mohit", },
{userId : 2, userName : "Ram", },
{userId : 3, userName : "shyam", },
{userId : 4, userName : "rangila", },
{userId : 5, userName : "santosh", },
];
const output = users.find((user)=>user.userId===3);
console.log(output);
// 👉 Every method
// if every conditon is satisfied then it will return true otherwise false
// callback function of every mehod return boolean (true/false)
// every method also return boolean (true/false)
const numbers = [2,4,6,8,10];
const isEven = numbers.every((num)=>num%2===0);
console.log(isEven);
// realistic example
const userCart = [
{productId: 1, productName: "mobile", price: 12000},
{productId: 2, productName: "laptop", price: 22000},
{productId: 3, productName: "tv", price: 15000},
]
const priceCheck = userCart.every((a)=>a.price<30000)
console.log(priceCheck);
// 👉 some method
const numbers = [1,3,2,5];
// is there any number which is even?
// if yes then it will return true otherwise false.
let ans = numbers.some((number)=>number%2===0);
console.log(ans);
// realistic examples :-
const userCart = [
{productId: 1, productName: "mobile", price: 12000},
{productId: 2, productName: "laptop", price: 22000},
{productId: 3, productName: "tv", price: 15000},
{productId: 3, productName: "macbook", price: 250000},
]
const checkingPrice = userCart.some((cartItems)=>cartItems.price>100000)
console.log(checkingPrice);
// 👉 fill method
// value , start , end
// it change original array
const fillWith0 = new Array(10).fill(0);
console.log(fillWith0);
const myArray = [1,2,3,4,5,6,7,8,9,10];
// here i want to fill 0 in place of 3,4,5
myArray.fill(0,2,5);
console.log(myArray);
// 👉 splice method
// it help us to delete or insert anything inside array
// it change original array
// start, delete, insert
const myArray = ["item1", "item2", "item3"]
// delete
let deletedItem = myArray.splice(1,1)
// it can even return the deleted items
console.log(" deleted item ",deletedItem); // deleted
console.log(myArray); // original
// insert
myArray.splice(1,0,"inserted item")
console.log(myArray);
// ❓ Delete and insert together
const Names = ["Mohit","Rohit","Jatin","Shekher"]
let deltedNames = Names.splice(1,2,"Ram","Shyam");
console.log("deltedNames",deltedNames);
console.log("added names ", Names);
// 🌟 Iterables 🌟
// jispe ham for off loop laga sakte hain
// ex : string , array are iterables
const myName = "Himanshu";
for(let char of myName){
console.log(char);
}
const items = ["item1","item2","item3"]
for (let item of items){
console.log(item);
}
// ❓ is object iterable?
// ➡️ no objects aren't iterable
// ex :-
// its wrong
// const users = {
// key1 : "value1",
// key2 : "value2",
// key3 : "value3",
// }
// for (let user of users){
// console.log(user);
// }
// output
// Uncaught TypeError: users is not iterable
// 🌟 array like object 🌟
// jinke pas length prperty hoti hai
// aur jinko ham index se access kar sakte hain
// example :- string
let gameName = "GTA V";
console.log(gameName.length);
console.log(gameName[4]);
// 🌟 SET 🌟
// 👉 it's iterable
// 👉 set return new array
// 👉 store data (it store linear data like arrays do )
// 👉 sets also have its own methods
// 👉 No index-based access
// 👉 Order is not guaranteed
// 👉 unique items only (no duplicate allowed)
// how to create set
let arrays = ["item1","item2"]
const numbers = new Set();
numbers.add(1);
numbers.add("a");
numbers.add(arrays);
// numbers.add(arrays); // we cant add this one because we already added
// but here we can add like this because we have different memory location
numbers.add(["cat","dog"])
numbers.add(["cat","dog"])
// 👉 has method
if(numbers.has(1)){
console.log("present");
}else{
console.log("not present");
}
// we can use for of loop here
for (let number of numbers){
console.log(number);
}
// we can use set to get unique elements from an array
let myArr = [4,4,5,5,7,6,2,4,1,1,1,1,1,1];
let uniqueElements = new Set(myArr);
console.log(uniqueElements);
// here we only get unique numbers not repeatable one
console.log(myArr);
// we cant use length property here so we have a trick to do this
length =0;
for (let elements of uniqueElements){
length++;
}
console.log(length);
// 🌟🌟 Maps 🌟🌟
// its not map method
// map is an iterable
// store data in orderd fashion
// store key value pair (like object)
// duplicate keys aren't allowed like objects
// different between maps and objects
// object can only have string or symbol
// as key
// in map you can use anything as key
// like array,number,string
// 👉 Object literals
// key -> string
// key -> symbol
// const person = {
// firstName : "Rohan",
// age : 12,
// 1 : "one"
// }
// console.log(person.firstName);
// console.log(person['firstName']);
// console.log(person[1]);
// 👉 How map works :-
const person = new Map();
person.set("firstName","Mohan");
person.set("age","12");
person.set(1,"one")
console.log(person);
// accessing
console.log(person.get(1));
for(let key of person.keys()){
console.log(key);
}
// nhi samjh aaya to chod diya :D
// 🌟 Clone using Object.assign 🌟
const obj = {
key1 : "value1",
key2 : "value2"
}
// const obj2 = obj
// adding data to obj
// obj.key3 = "value3"
// now the value will clone in obj2 too
// but if you dont want these changes in both objects
// then use (...) spread operator
// for ex
// const obj2 = {...obj} // in this obj value 3 is not added
// console.log(obj);
// console.log(obj2);
// Now Object.assign (it works like spread operator (...))
// how to clone
const obj2 = Object.assign({},obj);
obj.key3 = "value3"
console.log(obj);
console.log(obj2);
// 🌟 Optional chaining 🌟
const user = {
firstName : "ROHIT",
// address : {houseNumber : "1234"}
// jaise yaha address nhi hai lekin yaha error nahi ayega
// undefined aa jayega
}
// (?.) ham tab lagayenge jab koi chiz abhi ke liye exist na karti ho
// but in future yaha kuch data aa sakta hai ,
// us situation me hame error nhi chahiye to ham (.?) ka use karte hain
console.log(user.firstName);
console.log(user.address?.houseNumber);
// 🌟🌟 method 🌟🌟
// function inside object is called method
function personInfo(){
console.log(`${this.firstName}'s age is ${this.age}`);
}
const person1 = {
firstName : "Ram",
age : 10,
about : personInfo
}
const person2 = {
firstName : "shyam",
age : 24,
about : personInfo
}
const person3 = {
firstName : "sohan",
age : 19,
about : personInfo
}
person1.about()
person3.about()
person2.about()
// 🌟🌟 this keyword 🌟🌟
// 👉 this is a object
// 👉 The defination of 'this' object is that it contain the current context.
// The this object can have different value depending on where it is placed.
// 👉 this object not work with Fat arrow function
// "use strict" // use strict rhega to undefied ayega warna pura windows obj ayega
function myFunc(){
console.log(this);
}
myFunc()
// 🌟 this keyword in Arrow function 🌟
// 👉 arrow function doen't take this keyword
const user = {
firstName : "Ram",
age : 12,
about : myfun = () => console.log(this.firstName , this.age)
}
user.about()
// 🌟 call,apply,bind method🌟
// 👉 call()
// by using this we dont have to copy things /rename
const user1 = {
firstName : "aman",
age : 12,
about : function (hobby,favMusician){
console.log(this.firstName,this.age , hobby , favMusician);
}
}
const user2 = {
firstName : "sam",
age : 17,
}
// function borrowing
user1.about.call(user2,"guitar","justin bieber");
// 👉 apply method
// it works same like call but in apply we give arguments in array
user1.about.apply(user2,["games,one direction"])
// 👉 bind
// it never print , it return function
const func = user1.about.bind(user1,"Sleeping","alan walker");
func()
// 🌟 Short syntax 🌟
// 👉 Short syntax to create function/method in object
// 👉 funciton inside objects are method , so we can call it method
// const user1 = {
// firstName : "ABC",
// age : 5,
// about : function myFunc (){
// console.log("hello!");
// }
// }
const user1 = {
firstName : "ABC",
age : 5,
about(){
console.log("hello!");
}
}
// Both are correct
user1.about()
// // 🌟🌟 Date object 🌟🌟
// // let x = new Date();
// // console.log(x);
// let y = new Date(2022,11,13,10,06,33,7)
// console.log(y);
// // 👉 year > month > day > hours > minutes > second > millisecond
// // 👉 minimum requriment year and month
// // 👉 we can use as a string too
// let stringDate = new Date("October 13, 2017 , 11:12:13:4")
// console.log(stringDate);
// // 👉👉 get() method
// // we can get the values
// // 👉 how to get time in millisecond
// let getmillisecond = stringDate.getTime()
// console.log(getmillisecond);
// // 🛑 Note :- ye time hame computer ke banne se leke abhi tak
// // ka dikhata hai ! like 1970 se abhi tak ka !
// // 👉 How to get full year
// let getFullYear = stringDate.getFullYear();
// console.log(getFullYear);
// // 👉 How to get Month
// let getMonth = stringDate.getMonth();
// console.log(getMonth);
// // 👉 How to get date
// let getDate = stringDate.getDate();
// console.log(getDate);
// // 👉 How to get hours
// let getHours = stringDate.getHours();
// console.log(getHours);
// // 👉 How to get minutes
// let getMinutes = stringDate.getMinutes();
// console.log(getMinutes);
// // 👉 How to get seconds
// let getSecond = stringDate.getSeconds();
// console.log(getSecond);
// // 👉 How to get milliseconds
// let getMilisecond = stringDate.getMilliseconds();
// console.log(getMilisecond);
// 👉👉 set() method
// we can set/change the values
let myDate = new Date ("october 13, 2018 11:12:13:14");
// 👉 set Year
myDate.setFullYear(2020)
// 👉 set month
myDate.setMonth(2)
// 👉 set date
myDate.setDate(19);
// 👉 set hours
myDate.setHours(20);
// 👉 set minutes
myDate.setMinutes(1);
// 👉 set second
myDate.setSeconds(2);
// 👉 set millisecond
myDate.setMilliseconds(15);
// console.log(myDate);
// ❓ which day will be after 50 days of this date?
let x = new Date ("october 13, 2018 11:12:13:14");
let y = new Date ("october 13, 2018 11:12:13:14");
// now we changing the date and we will add 50 days to y
y.setDate(x.getDate() + 50);
console.log("( unchanded date) ",x);
console.log("( changed date) ",y);
// 👉 Compare Dates
let date1 = new Date("october 13, 2018 11:12:13:14");
let date2 = new Date();
if(date1>date2){
console.log("date 1 is future date");
}else if (date1<date2){
console.log("date 1 is past date");
}else{
console.log("equal date");
}
// 🌟🌟 New Keyword 🌟🌟
// 👉 it create object using constructor
let person1 = {
key1 : "value1"
}
console.log(person1.key1);
// new keyword
let person2 = new Object()
person2.key1 = "value1"
console.log(person2.key1);
// Both are same
// 🌟 Getter and Setter 🌟
// 👉👉 getter
// 👉 jab hame koi bhi propery ka value get karna hai manupulate/change kar ke
// object se bhar lana hai
var user = {
name : "Himanshu",
age : 19,
// getName : function (){
// return this.name.toUpperCase();
// }
get getName(){
return this.name.toUpperCase()
},
}
// console.log(user.getName()); here we using () because we accessing it like a method
// but here we dont use breaket because we using get method
console.log(user.getName);
// 👉 how to call
// 👉 method call by using bracket where propery call by only name
// 👉 but here we dont want to call as a method , we want to call as a propery
// 👉 here getter and setter help us , look on user object
// 👉👉 setter
// 👉 jab hame enter karte hue ya set karate hue property ko change karn hai
// to ham setter funciton ka use karte hain
// 👉 man lo ki mujhe hames apne naam ki value ko
// upercase me rkhna hai to ham yaha pe setter ka use kar sakte haiin
// ex
const user2 = {
name : "abhijeet",
age : 30,
set setName (n){
this.n =n.toUpperCase()
}
}
user2.setName = 'ramu'
console.log(user2.n);
// 🌟🌟🌟🌟 IMPORTANT 🌟🌟🌟🌟
// 🌟🌟 OBJECT CONSTRUCTOR 🌟🌟
// 👉 we use it jab hame key same rkhni hoti hai lekin
// hame values change chahiye hoti hai to we use it
// 👉 js devloper es6 se pehle yahi use karte the kyuki
// us time class nhi hua karte the js me
// 🛑 Note :- Object constructor banate time name ka first letter hame capital rkhna chahiye
// var student = {
// firstName : "Ajit",
// lastName : "Kumar",
// age : 15,
// class : 9
// }
// agr hame or v banane hai to copy karke value change karna hoga
// isiliye new tarika hai iska obj constructor
function Students (first,last,age,cls){
this.firstName = first;
this.lastName = last;
this.age = age;
this.class = cls;
this.fullName = function(){
return this.firstName + " " +this.lastName
}
}
var student1 = new Students("Ajit","kumar",15,9);
var student2 = new Students("Sujeet","tiwari",24,12);
// 👉 how to add propety
student1.nationality = "India"
// how to add method
student1.about = function (){
return `${this.firstName} ${this.lastName} is a good boy`
}
console.log(student1.about());
console.log(student1.fullName())
// 🌟🌟🌟🌟 IMPORTANT 🌟🌟🌟🌟
// 🌟🌟 OBJECT CONSTRUCTOR 🌟🌟
// 👉 we use it jab hame key same rkhni hoti hai lekin
// hame values change chahiye hoti hai to we use it
// 👉 js devloper es6 se pehle yahi use karte the kyuki
// us time class nhi hua karte the js me
// 🛑 Note :- Object constructor banate time name ka first letter hame capital rkhna chahiye
// var student = {
// firstName : "Ajit",
// lastName : "Kumar",
// age : 15,
// class : 9
// }
// agr hame or v banane hai to copy karke value change karna hoga
// isiliye new tarika hai iska obj constructor
function Students (first,last,age,cls){
this.firstName = first;
this.lastName = last;
this.age = age;
this.class = cls;
this.fullName = function(){
return this.firstName + " " +this.lastName
}
}
var student1 = new Students("Ajit","kumar",15,9);
var student2 = new Students("Sujeet","tiwari",24,12);
// 👉 how to add propety
student1.nationality = "India"
// how to add method
student1.about = function (){
return `${this.firstName} ${this.lastName} is a good boy`
}
console.log(student1.about());
console.log(student1.fullName())
// 🌟🌟 class 🌟🌟
class CreateUser{
// 👉 its a templete which help us to crate an object
constructor(firstName,lastName,email,age,address){
this.firstName = firstName;
this.lastlastName =lastName;
this.email = email;
this.age = age;
this.address = address;
}
about(){
return this.firstName + "'s age is " + this.age
}
}
// 👉 new keyword is neccessary
const user1 = new CreateUser("ajit","kumar","abc@gmail.com",19,"address1")
console.log(user1.firstName);
console.log(Object.getPrototypeOf(user1));
// 👉 Class practise and extended keyword
class Animal {
constructor(name,age){
this.name = name;
this.age = age;
}
eat(){
return `${this.name} is eating`;
}
isSuperCute(){
return this.age <= 1;
}
isCute(){
return true;
}
}
const animal1 = new Animal("kitty",1);
console.log(animal1);
// 👉 Extended keywords
class Dog extends Animal{
constructor(name,age,speed){
// 👉 Super keywords
// super is used for getting prarent's value
super(name,age);
this.speed = speed;
}
run(){
return `${this.name} is running at a speed of ${this.speed}`
}
}
// 👉 object or instance are same
const animal2 = new Dog("tommy",1,45);
console.log(animal2.run());
// another one
const emp1 = new Human("Ajit",112);
const emp2 = new Human("ranjit",99)
class Gender extends Human{
constructor(name,iq,gender){
super(name,iq)
this.gender = gender
}
findGender(){
if(this.gender == "male" || this.gender == "MALE" || this.gender == "Male"){
return `${this.name} is Male`
}else if(this.gender == "female" || this.gender == "FEMALE" || this.gender == "Female"){
return `${this.name} is female`
}
}
// we cant use this keyword in static
static mulNum(a,b){
return a*b
}
}
const emp4 = new Gender("Akash",102,'male');
const emp5 = new Gender("sneha",99,"female");
console.log(Gender.mulNum(2,2))
// 🌟🌟🌟🌟🌟🌟PHASES🌟🌟🌟🌟🌟🌟
// 👉 compilation
// 1. because of early error checking
// 2. hame determine karna hota hai hai
// appropriate scope kya hain variables
// ke liye
// 👉 code execution
// 1. code ko execute karne ke liye hame
// execution context create karna hoga
// 2. sabse pehle jo execution context create
// hota hai usko ham GLOBAL execution context
// bolte hain
// 🌟 Two phases of GLOBAL execution context
// ➡️ creation phase
// ➡️ code execution phase
// 👉 why compilation
// 👉 how javascript code executes
// 👉 what is global execution context
// 👉 what is local execution context
console.log(this);
console.log(window);
console.log(firstName);
var firstName = "Ajit";
console.log(firstName);
// 🌟HOISTING🌟
// In JavaScript, Hoisting is the default behavior of moving all the declarations
// at the top of the scope before code execution. Basically, it gives us an advantage
// that no matter where functions and variables are declared, they are moved to the
// top of their scope regardless of whether their scope is global or local.
// 👉 it only take decleration on top // only var x not 'hello'
// console.log(x);
// var x = "hello"
// console.log(x);
// let x = 7;
// 👉 hoisting work with let and const too but js doesn't give undefied to itself
// thats why this error comes (Cannot access 'x' before initialization)
// 🌟closures🌟
// A closure is the combination of a function bundled together (elclosed)
// with references to its surrounfing state (the lexical environment).
// In other words, a closure gives you access to an
// outer function's scope from an inner function.
// In JavaScript, closure are created every time a function is created,
// at function creation time.
// 👉 function can return function
function outerFunction(){
function innerFunction(){
return "hello world";
}
return innerFunction;
}
const ans = outerFunction();
console.log(ans());
// 🌟select element using get element by id🌟
const mainHeadingGEBI = document.getElementById('main-heading');
console.log(mainHeadingGEBI);
// 🌟select element using query selector🌟
// we can select class or id or anything(h1,a,p) by using query selector
const mainHeadingQS = document.querySelector("#main-heading");
const header = document.querySelector('.header');
// // 👉 only one navlist if we use querySelector
const navItem = document.querySelector('.nav-item');
console.log(navItem);
// // 👉 if we want all nav items then we can use querySelctorAll
const allNavItems = document.querySelectorAll('.nav-item');
console.log(allNavItems);
// 🌟Text content and inner Text🌟
// 👉 text content -> ye hame sara text dega console pe
// agar hamne wo browser se hide bhi kar rkha hai wo bhi
// 👉 inner text -> ye bas hame wahi text dega jo browser pe
// show ho rha ho
const mainHeading = document.getElementById('main-heading');
console.log(mainHeading.textContent);
const chandedText = mainHeading.textContent = "changed text";
console.log(chandedText); // pehle "manage ur task tha" ab 'changed text ho gya'
// 🌟🌟 change the style of elements 🌟🌟
const changeColor = document.querySelector('div.headline h2');
changeColor.style.color = "red";
changeColor.style.backgroundColor = "yellow"
// 🌟🌟 get and set attributes 🌟🌟
// attribute = link/href
// get attributes
const link = document.querySelector('a');
console.log(link.getAttribute("href").slice(1));
// const mainHeadingText = document.querySelector('.form-todo input');
// const ans = mainHeadingText.getAttribute('type');
// console.log(ans);
// set attributes
link.setAttribute('href',"hello");
console.log(link);
console.log(link.getAttribute("href"));
// get multiple elements using getElement by class name
// const navItem = document.getElementsByClassName('nav-item'); // HTML selection
// console.log(navItem[0]);
// get multiple elements items using querySelectorAll
const navItem = document.querySelectorAll('nav-item');
console.log(navItem);
// 🌟 Loop 🌟
// 👉 we cannot use foreach to iterate html collection
// 👉 but we can change html collection to array then
// we can use foreach
// 👉 array like object -> indexing , length
let navItems = document.getElementsByTagName('a');
for(let i = 0; i<navItems.length; i++){
const navItem = navItems[i];
navItem.style.color = "red";
navItem.style.backgroundColor = "yellow";
}
// for(let navItem of navItems){
// navItem.style.color = 'red'
// }
// 👉 here we can change html collection into array
navItems = Array.from(navItems);
// 👉 and now we can use forEach
navItems.forEach((navItem)=>{
navItem.style.color = "blue"
})
// 👉 query selector se hame element nodes me milte hain
// means ham uspe direct koi v loops laga sakte hain
// including foreach loops v
const navLists = document.querySelectorAll('.a'); // Node lists []
navLists.forEach((navList)=>{
navList.style.backgroundColor = "cyan"
})
// 🌟🌟 Inner HTML 🌟🌟
let headline = document.querySelector('.headline');
headline.innerHTML = "<h1>Hello world</h1>";
// 🌟DOM Traversing🌟
// 👉 childNode
const rootNode = document.getRootNode();
const htmlElements = rootNode.childNodes[0];
// console.log(htmlElements.childNodes);// nodeList(3) [head,text,body]
const headElementNode = htmlElements.childNodes[0]
const textElementNode = htmlElements.childNodes[1]
const bodyElementNode = htmlElements.childNodes[2]
// console.log(headElementNode);
// 👉 Parent node
const parentNode = textElementNode.parentNode
// console.log(parentNode); // html
// 👉 sibling relationship
const sibling = headElementNode.nextSibling;
console.log(sibling); // text node
console.log(sibling.nextElementSibling); // body element
// 👉 nextElementSibling white spaces ko ignore karta hai
// 👉 direct selection
const body = document.body;
console.log(body);
// 👉 we can use selector to any element
const head = document.getElementById('head');
const title = head.querySelector('title')
console.log(title.childNodes);
// 👉 children
const container = document.querySelector('.container');
console.log(container.children);
// 🌟classList , add , remove and toggle classes🌟
// 👉 add class
const todoSection = document.querySelector(".section-todo");
// todoSection.classList.add('bg-dark')
// 👉 remove class
// todoSection.classList.remove('container')
// 👉 contain
const ans = todoSection.classList.contains('container');
// console.log(ans);
// 👉 toggle
// jo class hoga usko remove karega
// jo nhi hai usko add kar deta hai
// todoSection.classList.toggle('bg-dark')
// todoSection.classList.toggle('bg-dark')
// 🌟Add html element using javascript🌟
const todoList = document.querySelector('.todo-list');
// todoList.innerHTML = "<li>first todo</li>"
// todoList.innerHTML = todoList.innerHTML + "<li>2nd todo</li>"
// 👉 this isnt a good method to do this it decrese
// website's performence
// document.createElement()
// append
// prepend
// remove
// before
// after
// 👉 document.createElement()
// for creating new element
const newTodo = document.createElement("li");
newTodo.textContent = "Eat snacks";
const todoList = document.querySelector('.todo-list');
// 👉 append
todoList.append(newTodo); // piche
// 👉 prepend
todoList.prepend(newTodo); // aage
// 👉 remove
const todo1 = document.querySelector('.todo-list li');
todo1.remove()
// 🌟 clone nodes 🌟
const ul = document.querySelector('.todo-list');
const li = document.createElement("li");
li.textContent = "cloned todo";
const li2 = li.cloneNode(true)
// 👉 true karne se everything(child,elem,etc) clone ho jayega
ul.append(li)
ul.prepend(li2)
// 🌟 Static List vs Live List 🌟
// 👉 querySelectorAll hamein static list degi
// 👉 getElementBySomething hamein live list degi
// 🌟 How to get dimension of element 🌟
// height width
const sectionTodo = document.querySelector('.section-todo');
const info = sectionTodo.getBoundingClientRect()
console.log(info.height);
// 🌟 Event 🌟
// click
// button press
// mouse hover
const btn = document.querySelector('.btn-headline');
// method -----> add event listner
btn.addEventListener('click', ()=>{
console.log("clicked");
})
// this keyword
const btn = document.querySelector('.btn-headline');
btn.addEventListener("click",function(){
console.log("clicked");
console.log("value of this");
console.log(this);
})
// 🌟 click event on multiple buttons 🌟
const allBtn = document.querySelectorAll('button');
for(let btn of allBtn){
btn.addEventListener('click',()=>{
console.log(btn.textContent);
})
}
// 🌟 event object 🌟
// const firstButton = document.querySelector("#one");
// firstButton.addEventListener('click',function(event){
// console.log(event);
// })
// jab bhi mai kisi bhi element pe event listener add hoga
// js Engine --- line by line execute karta hai
// browser ---- js Engine + extra features
// browser ----- js Engine + WebApi
// jab browser ko pata chala ki user ne event perform kia
// jo hum listen kar rahe hai
// browser ----- 2
// 1.) callback function hai vo js Engine ko degi ......
// 2.) callback function ke sath browser jo event hua hai uski information bhi dega
// ye info hamein ek object ke form mai milegi
const allBtn = document.querySelectorAll('.my-buttons button');
for(let i=0; i<=allBtn.length; i++){
allBtn[i].addEventListener("click",function(e){
console.log(e.currentTarget)
})
}
// practise 1
const buttons = document.querySelectorAll(".my-buttons");
for(let btn of buttons){
btn.addEventListener('click',(e)=>{
e.target.style.backgroundColor = 'yellow';
e.target.style.color = 'green';
})
}
// Project
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./little-demo.css">
<script src="./19.js" defer></script>
<title>Random Colors</title>
</head>
<body class="body">
<main>
<div class="container">
<h1>Current Color : <span class="current-color"> rgb(255,255,255) </span> </h1>
<button>Change Background Color</button>
</div>
</main>
</body>
</html>
// color changing project
const btn = document.querySelector('button');
const body = document.querySelector('.body');
const currentColor = document.querySelector('.current-color')
// random color
function randomColorGenerator(){
const red = Math.floor(Math.random()*256);
const green = Math.floor(Math.random()*256);
const blue = Math.floor(Math.random()*256);
const randomColor = `rgb(${red},${green},${blue})`
return randomColor
}
btn.addEventListener('click',()=>{
const randomColor = randomColorGenerator();
body.style.backgroundColor = randomColor;
currentColor.textContent = randomColor
})
// 🌟 Keyboard and mouse event 🌟
// 👉 keyboard
const body = document.body;
body.addEventListener('keypress',(e)=>console.log(e.key))
//👉 mouse
const mainBtn = document.querySelector('.btn-headline');
mainBtn.addEventListener('mouseover',function(){
console.log("mouseover even occur");
})
mainBtn.addEventListener('mouseleave',function(){
console.log("leave even occur");
})
// many more
<title>Event Bubbling | Capturing | delegation</title>
</head>
<body>
<main>
<div class="grandparent box">
Grandparent
<div class="parent box">
Parent
<div class="child box">Child</div>
</div>
</div>
</main>
</body>
// 🌟🌟
// 👉 event bubbline / propagation
// 👉 event capuring
// 👉 event delegation
// console.log("hello world");
const grandparent = document.querySelector(".grandparent");
// const parent = document.querySelector(".parent");
// const child = document.querySelector(".child");
// capturing events
// child.addEventListener(
// "click",
// () => {
// console.log("capture !!!! child");
// },
// true
// );
// parent.addEventListener(
// "click",
// () => {
// console.log("capture !!!! parent");
// },
// true
// );
// grandparent.addEventListener(
// "click",
// () => {
// console.log("capture !!!! grandparent");
// },
// true
// );
// document.body.addEventListener(
// "click",
// () => {
// console.log("capture !!!! document.body");
// },
// true
// );
///// not capture
// child.addEventListener("click", () => {
// console.log("bubble child");
// });
// parent.addEventListener("click", () => {
// console.log("bubble parent");
// });
// grandparent.addEventListener("click", () => {
// console.log("bubble grandparent");
// });
// document.body.addEventListener("click", () => {
// console.log("bubble document.body");
// });
// 👉 event delegation
// grandparent.addEventListener("click", (e) => {
// console.log(e.target);
// });
<!-- todo -->
<script src="22_todo.js" defer></script>
<header class="header">
<nav class="nav container">
<h1 class="logo">Website</h1>
<ul class="nav-items">
<li class="nav-item"><a class="a" href="#home">Home</a></li>
<li class="nav-item"><a class="a" href="">Todo</a></li>
<li class="nav-item"><a class="a" href="">Sign Up</a></li>
</ul>
</nav>
<div class="headline">
<h2 id="main-heading">
Manage your tasks <span style="display: none">Hello</span>
</h2>
<button class="btn btn-headline">Learn More</button>
</div>
</header>
<section class="section-todo container">
<h2>Your plan for today ?</h2>
<!-- todo form -->
<form class="form-todo">
<input type="text" name="" id="todo-input-text" placeholder="Add Todo" />
<input type="submit" value="Add Todo" class="btn" />
</form>
<ul class="todo-list">
<li>
<span class="text">Do this do that</span>
<div class="todo-buttons">
<button class="todo-btn done">Done</button>
<button class="todo-btn remove">Remove</button>
</div>
</li>
</ul>
</section>
const todoForm = document.querySelector(".form-todo");
const todoInput = document.querySelector("#todo-input-text");
const todoList = document.querySelector(".todo-list");
todoForm.addEventListener('submit', (e) => {
e.preventDefault() // it help to stop refreshing the page
const newTodoText = todoInput.value;
const newLi = document.createElement("li");
const newLiInnerHTML = `
<span class="text">${newTodoText}</span>
<div class="todo-buttons">
<button class="todo-btn done">Done</button>
<button class="todo-btn remove">Remove</button>
</div>
`
newLi.innerHTML = newLiInnerHTML
todoList.prepend(newLi)
todoInput.value = "";
})
todoList.addEventListener('click',(e)=>{
if(e.target.classList.contains('remove')){
const targetedLi = e.target.parentNode.parentNode;
targetedLi.remove()
}
if(e.target.classList.contains('done')){
const liSpan = e.target.parentNode.previousElementSibling;
liSpan.style.textDecoration = "line-through"
}
})
/// JS part 3
// 🌟 synchronous programming vs asynchronous programming 🌟
// 👉 synchronous programming
// 👉 js is a synchronous programming single threaded language
// 👉 synchronous programming code ko line by line read karta hai
// jab tak ek kaaam kahatam nahi hoga tab tak dusra kaam nahi hoga
// 👉 jaise yahan jab tak for loop ka kaam khatam nahi hoga tabtak
// script ended print nhi hoga
// console.log("script started");
// for(let i=0; i<10000; i++){
// console.log("inside for loop");
// }
// console.log("script ended");
// 🌟 asynchronous programming
// 👉 javscript asynchronous programming languge nahi hai lekin ham fir bhi js me
// asynchronous programming kar pate hain kyuki bhale hi js asynchronous programming
// language na ho lekin ye kam ham web api ki madad se kar pate hain
// take a look
// 🌟🌟🌟 setTimeout 🌟🌟🌟
// console.log("script start");
// setTimeout(()=>{
// console.log("hello world");
// },1000);
// console.log('script ended');
// 🛑 setTimeOut ham kisi v chiz ko delay karne ke liye use karte hain
// 🛑 setTimeOut hame return me hamesa ek id deta hai
// 🛑 jab tak setTimeOut ka data print nhi hoga tab tak age ke kam hote rhenge
// or aisa synchronous me nhi hota hai lekin ham web api ki madad se ise(asynchronous)
// kar sakte hain
// 👉 Id
console.log("script start");
let setTimeoutId = setTimeout(() => {
console.log("hello there");
},0);
console.log(setTimeoutId); // here we get Id
console.log("script end");
// console printing pattern
// script start ➡️ 1(id) ➡️ script end ➡️ hello there
// 🌟 clearTimeout
// 👉 clear timeout se ham setTimeout ko finish/kill/rok sakte hein
// uski id ki help se
clearTimeout(setTimeoutId)
// now in console "hello there" will not print
// because we cleared the settimeout function
// 🌟 set Interval
// 👉 jab hame kisi nischit samaye pe koi chiz bar bar chahhiye
// to ham set interval ka use karte hain
console.log("script start");
const setIntervalID = setInterval(()=>{
console.log("inside set interval");
},1000)
console.log("script end");
// 👉 clear interval
// clear interval ham tab use karenge jab hame setInterval ko
// rokna ho
// 👉 ID
// set interval v hame ek id deti hai jiski madad se ham koi task
// perform kar sakte hain like clearInterval
clearInterval(setIntervalID)
// 🌟 Callback 🌟
// const datas = [
// {name:"ajit",profession:"engineer"},
// {name:"anuj",profession:"engineer"},
// ]
// function getDatas(){
// setTimeout(()=>{
// datas.forEach((data)=>{
// console.log(data.name);
// })
// },1000)
// }
// function createData(newData,callback){
// setTimeout(()=>{
// datas.push(newData);
// // 👉 this value will not print
// callback()
// // 👉 now this will print
// },2000)
// }
// createData({name:"monu",profession:'video creator'},getDatas)
// 🌟🌟 Callback hell 🌟🌟
let heading1 = document.querySelector('.heading1');
let heading2 = document.querySelector('.heading2')
let heading3 = document.querySelector('.heading3')
let heading4 = document.querySelector('.heading4')
let heading5 = document.querySelector('.heading5')
// setTimeout(()=>{
// heading1.textContent = "one";
// heading1.style.color = "violet";
// setTimeout(()=>{
// heading2.textContent = "two";
// heading2.style.color = "purple";
// setTimeout(()=>{
// heading3.textContent = "three";
// heading3.style.color = "red";
// setTimeout(()=>{
// heading4.textContent = "four";
// heading4.style.color = "pink";
// setTimeout(() => {
// heading5.textContent = "five";
// heading5.style.color = "green"
// }, 5000);
// },4000)
// },3000)
// },2000)
// },1000)
// 👉 Doing same thing with functions
// function changeText(element,text,color,time){
// if(element!=null){
// setTimeout(()=>{
// element.textContent = text;
// element.style.color = color;
// },time)
// }else{
// console.log("your element doesn't exist");
// }
// }
// changeText(heading1,"one","pink",1000);
// 👉👉 Scenario
// 1. Register
// 2. Send welcome Email
// 3. Login
// 4. Get-user data
// 5. Display user data
// i want to give time to register function before all other function.
// Hindi me bole to callback function hm tab use karenge jab hame kisi
// ek task ko complete hone ke bad dusra task karrna ho to ham
// call back funciton ka use karte hain
// down below i use call back
// CALL BACK
function register(callback) {
setTimeout(() => {
console.log("resgister end");
callback();
}, 2000);
}
function sendEmail(callback) {
setTimeout(() => {
console.log("Email send");
callback();
}, 3000);
}
function login(callback) {
setTimeout(() => {
console.log("Logoin end");
callback();
}, 1000);
}
function getUserData() {
setTimeout(() => {
console.log("Got user data");
}, 1000);
}
function DisplayUserData() {
setTimeout(() => {
console.log("User data displayed");
}, 1000);
}
// This is callback function :--
// call back hell
register(function (){
sendEmail(function(){
login(function(){
getUserData(function(){
DisplayUserData();
});
});
});
});
console.log("other application work is doing fine");
// This is not a good practise :-
// Thats why we use promises..
// 🌟🌟 Promises 🌟🌟
// 👉 future value is the older name of promise
// 👉 promise is feature of browser not js
// 👉 promise is asynchronous
// 👉 promise is a object
console.log("script start");
let player = ["Rohit" , "Virat" , "Dhoni"];
let myPlayer = new Promise((resolve,reject)=>{
if(player.includes("Rohit") && player.includes("Virat") && player.includes("Dhoni")){
resolve("I will win the game")
}else{
reject("I cant win the game without them")
}
});
// produce
// consume
// how to consume
// myPlayer.then((res)=>{
// // 👉 jab promise resolve hoga
// console.log(res);
// // 👉 jab promise reject hoga
// },(error)=>{
// console.log(error);
// })
// 👉 ye bhi same kam karega lekin yaha hame 2 callback
// function likhne ki jarurat nahi hai just like uper
// me ham likhte the . ham simply catch ko use kar sakte hain
myPlayer.then((res)=>{
console.log(res);
}).catch((error)=>{
console.log(error);
})
// 👉 proving that its a synchronous programm
for(let i=0; i<10; i++){
console.log(Math.random())
}
console.log("script end");
// 🌟 function returning promise 🌟
let player = ["Rohit" , "Virat" , "Dhoni"];
function myPlayer() {
return new Promise((resolve,reject)=>{
if(player.includes("Rohit") && player.includes("Virat") && player.includes("Dhoni")){
resolve("I will win the game")
}else{
reject("I cant win the game without them")
}
});
}
myPlayer().then((res)=>{
console.log(res);
}).catch((error)=>{
console.log(error);
})
// 🌟🌟 promise and setTimeout 🌟🌟
// i want to resolve / reject after 2 seconds
function myPromise (){
return new Promise((resolve,reject)=>{
const value = false;
setTimeout(() => {
if(value){
resolve();
}else{
reject()
}
}, 2000);
})
}
myPromise()
.then(()=>conole.log("resolved"))
.catch(()=>console.log("rejected"))
// 🌟 promise chaning 🌟
function myPromise(){
return new Promise((resolve,reject)=>{
resolve("Ajit")
})
}
myPromise()
.then((value)=>{ return value=value+"Kumar"})
.then((value)=>{return value=value+"Singh"})
.then((value)=>console.log(value))
// 🌟then🌟
// 👉 then method always return promise
// 👉 yha pe hamesa ye promise return kar rha hai
// tabhi ham then method laga paa rhe hain
// 🌟🌟 callback hell to flat code 🌟🌟
const heading1 = document.querySelector(".heading1")
const heading2 = document.querySelector(".heading2")
const heading3 = document.querySelector(".heading3")
const heading4 = document.querySelector(".heading4")
const heading5 = document.querySelector(".heading5")
function changeElement(element,text,color,time){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
if(element!=null){
resolve("all set")
element.textContent = text;
element.style.color = color;
}else{
reject("something went wrong , please check your code")
}
},time)
})
}
changeElement(heading1,"one","red",1000)
.then(()=>{return changeElement(heading2,"two","blue",2000)})
.then(()=>{return changeElement(heading3,"three","yellow",2000)})
.then(()=>{return changeElement(heading4,"four","pink",2000)})
.then(()=>{return changeElement(heading5,"five","green",2000)})
.catch((err)=>{console.log(err)})
// 🌟🌟 AJAX 🌟🌟
// BASIC THEORY
// AJAX : asynchronous javascript and XML
// HTTP request (hyper text transfer protocall)
// AJAX is a set of "web development techniques"
// using many web technologies on the "client-side "
// to create asynchronous web applications.
// With Ajax, web applications can send and retrieve
// data from a server asynchronously (in the background)
// without interfering with the display and
// behaviour of the existing page
// We don't use data in XML format anymore.
// we use JSON now.
// we have 3 most common ways to create and send request to server
// 1.) xmlHTTPRequest (old way of doing)
// 2.) fetch API (new way of doing)
// 3.) axios (this is third party library)
// 🌟Fetch🌟
// 👉 GET
// const URL = "https://jsonplaceholder.typicode.com/posts";
// fetch(URL)
// .then((res)=>{
// if(res.ok!=false){
// return res.json();
// }else{
// throw new Error("something went wrong !!")
// }
// })
// .then((data)=>{
// console.log(data);
// })
// // 👉 jab internet nhi rehega tab catch chalega
// .catch((error)=>{
// console.log("inside catch");
// console.log(error);
// })
// 👉 POST
const URL = "https://jsonplaceholder.typicode.com/posts";
fetch(URL,{
method: 'POST',
body: JSON.stringify({
title : 'foo',
body : 'bar',
userId : 1
}),
headers: {
'Content-type' : 'application/json'
}
})
.then((res)=>{
return res.json()
})
.then((data)=>{
console.log(data);
})
// 🌟🌟 ASYNC AWAIT 🌟🌟
const URL = "https://jsonplaceholder.typicode.com/posts";
// 👉 first with then
// fetch(URL)
// .then((res)=>{
// return res.json()
// }).then((data)=>{
// console.log(data);
// })
// 👉 async await
// 👉 function ke age async lagane se wo hamesa ek promise return karega
// aur await tab tak wait karega jab tak wo resolve nahi ho jata
async function getPost () {
const response = await fetch(URL);
const data = await response.json()
return data;
}
getPost()
.then((myData)=>{
console.log(myData);
})
.catch((err)=>console.log(err))
⭐⭐ LOCAL STORAGE AND SESSION STORAGE
LOCAL STORAGE :
// It always store data in form of key value pair which must be in string
// local storage's space is larger
// local storage data will never be deleted after the browser will close or on tab changes
// we can delete this data manually or by using local storage methods
const input = document.querySelector(".input-text");
const addBtn = document.querySelector(".add");
const deleteBtn = document.querySelector(".delete");
const printBtn = document.querySelector(".print");
addBtn.addEventListener("click", () => {
console.log(input.value);
// localStorage.setItem("key", input.value);
// in case of storing object or array we can first change it into string
localStorage.setItem(
"key",
JSON.stringify({ name: "marvin", surname: "allen" })
);
});
deleteBtn.addEventListener("click", () => {
localStorage.removeItem("key");
});
/**
* If we want to access that storage data back then first we need to convert that string into JSON format
* with the help of JSON.parse() and then we can get the data from local storage
* */
// ex
printBtn.addEventListener("click", () => {
console.log(JSON.parse(localStorage.getItem("key")));
});
SESSION STORAGE:
// session storage's space is smaller
// session storage data will be deleted after the browser will close or on tab changing
const input = document.querySelector(".input-text");
const addBtn = document.querySelector(".add");
const deleteBtn = document.querySelector(".delete");
const getVal = () => {
console.log(input.value);
sessionStorage.setItem("key", input.value);
};
addBtn.addEventListener("click", getVal);
const deleteVal = () => {
sessionStorage.removeItem("key");
};
deleteBtn.addEventListener("click", deleteVal);
THE END