// variable Intro // variable can store some information // we can use this information later //we can change this information later // variable declare //var firstName = "harshit" // we declare variable which is firstName // var is keywords // for variable declare we use var keywords // use of variable //console.log(firstName) // Output: harshit // variable name is sensitive //console.log(firstname) // ReferenceError // which type we declared we have to use on console.log also variable name // change value //firstName='mohit' //console.log(firstName) // Output: mohit // we don't needed to write var again,we used var for declared variable, //we already declared variable // if we write var again no problem // if don't used keywords that time also we declared variable //firstName = 'harshit' //console.log(firstName) // Output: harshit //firstname ='mohit' //console.log(firstname) // Output: mohit // javascript gives some freedom to use variable without used keywords // use stict // use strict used for the without using var keywords its show error //"use strict"; //firstName='harshit' //console.log(firstName) //Output: //index.js:54 //firstName='harshit' ReferenceError: firstName is not defined // then we used keywords var //var firstName = 'harshit' //console.log(firstName ) // Output: harshit //firstname='mohit' //console.log(firstname) //Output: //index.js:70 //firstName='mohit' //ReferenceError: firstname is not defined //var firstname ='mohit' //console.log(firstname) //Output:mohit //Rules for naming variable // you can't start with number // example //1value(invalid) //var 1value=10 //console.log(1value) // Output:SyntaxError:invalid and unexpected token //value1(valid) //var value1= 10 //console.log(value1) //console.log(value1**2) // Output:10 // Output: 100 // you can use underscore _ or dollar symbol //first_Name(valid) //_firstName(valid) //var _firstName='harshit' //console.log(_firstName) // Output: harshit //$firstName(valid) //first$Name(valid) //var $firstName='harshit' //console.log($firstName) //Output: harshit // You can't use spaces // first Name (invalid) //var first Name ='harshit' //console.log(first Name) // Output: SyntaxError:unexpected identifier // var first_name= 'harshit' //snake case writing // we using two letters between _ underscore we say snake case writing // var firstName ='harshit'// camel case writing //convention // start with small letter and use camel case writing // let keywords // declare variable with let keywords // ES 2015 let keywords comes //let firstName ='harshit' //console.log(firstName) // Output : harshit //var firstName ='harshit' //var firstName ='mohit'// we can use var already declare in it don't give error,if we use var again same name variable also //console.log(firstName) // Output: mohit //let firstName = 'harshit' //let firstName ='mohit' //console.log(firstName) //Output: //index.js:163 //let firstName = 'harshit' SyntaxError: Identifier 'firstName' has already been declared // we can't declared same name variable again with let keywords //let firstName ='harshit' //firstName = 'mohit' //console.log(firstName) //Output: mohit // if we can't declared same name variable with let keywords its dont occurs error // but we can use same variable without using let keywords // we can declared same name already declared variable with new string // var is which variable will be change // block scope vs function scope // declare constant //const pi = 3.14; //console.log(pi) //Output: 3.14 // const declared we can stated //const pi = 3.14 //pi = 3.15; //console.log(pi) //Output : TypeError: Assignment to constant variable //const pi = 3.14; //console.log(pi*2*2) //Output : 12.56 // string indexing //let firstName = 'harshit' //console.log(firstName[3]) // Output : s // h a r s h i t // 0 1 2 3 4 5 6 // length of string // firstName.length // last index : length - 1 //let firstName = 'harshit' //console.log(firstName.length) // Output: 7 // length will count from start from 1 ,in that character // index is start from 0 //let firstName = 'harshit ' //console.log(firstName.length) // Output : 9 // spaces also count // lat index : length - 1 //let firstName ='harshit' //console.log(firstName[firstName.length-1]) // Output: t // string methods // 1. trim() // 2.toUpperCase() // 3.toLowerCase() // 4.slice //1. trim() //let firstName =' harshit ' //console.log(firstName.length) //Output: 11 //let firstName =' harshit ' //console.log(firstName.length) //firstName.trim() //console.log(firstName.length) // Output : 11 // Output: 11 // string is immutable we can't change its content if we try to change the content with those change new object will be created // now we have to create new objects //let firstName = ' harshit ' //console.log(firstName.length) //let newString= firstName.trim() //console.log(newString) //console.log(newString.length) // Output: 11 // Output: harshit // Output: 7 //let firstName = ' harshit ' //console.log(firstName.length) //firstName = firstName.trim() //console.log(firstName) //console.log(firstName.length) // Output: 11 // Output: harshit // Output: 7 // 2. toUpperCase() //let firstName = 'harshit' //console.log(firstName.toUpperCase()) // Output : HARSHIT //let firstName = 'harshit' //firstName = firstName.toUpperCase()// string is immutable, toUpperCase() also give new string that's why we assign in new string //console.log(firstName) // Output: HARSHIT //3.toLowerCase() //let firstName = 'HARSHIT' //console.log(firstName.toLowerCase()) //Output : harshit //let firstName ='HARSHIT' //firstName = firstName.toLowerCase()// string is immutable ,toLowerCase() we assign in new string //console.log(firstName) //Output: harshit //4. slice() //start index includes //end index exculed //let firstName = 'harshit' //let newString= firstNamel.slice(0,5) //console.log(newString) // Output: harsh //let firstName = 'harshit' //let newString= firstName.slice(1,5) //console.log(newString) // Output: arsh //let firstName = 'harshit' //let newString = firstName.slice(1) //console.log(newString) // Output : arshit //typeof operator //data types (primitive data type) //sting : 'harshit' //number 2,5,6.7 //boolean //undefined //null //BigInt //symbol // string and number //let age = 22 //let firstName = 'harshit' //console.log(typeof age) //Output: number //console.log(typeof firstName) //Output: string //console.log(typeof 'harshit') // Output : string //console.log(typeof 7) // Output : number ////convert number to string //let age = 22 //console.log(typeof(age+"")) // Output: string //let age = 22 //age = age+"" //console.log(typeof age) // Output : string //let age = 23 //age = String(age) //console.log(typeof age) // Output: string ////convert string to number //let mystr = +"23" //console.log(typeof mystr) // number //let age = "23" //age = Number(age) //console.log(typeof age) // Output : Number //// sting concatenate //let string1 = 'harshit' //let string2 = 'vashistha' //console.log(string1 + " " + string2) // Output: harshit vashistha //let string1 = 'harshit' //let string2 = 'vashistha' //let fullName = string1 + ' ' + string2 //console.log(fullName) // Output: harshit vashistha //let string1 = "23" //let string2 = "7" //let myStr = string1 + string2 //console.log(myStr) //console.log(typeof myStr) // Output : 237 // Output : string //let string1 = "23" //let string2 = "7" //let myStr = +string1 + +string2 //console.log(myStr) //console.log(typeof myStr) // Output : 30 // Output :number //let string1 = "23" //let string2 = "7" //let myStr = Number(string1 + string2) //console.log(myStr) //console.log(typeof myStr) // Output : 30 // Output : number //// template string // tidous to do //let firstName = 'harshit' //let age = 22 //let aboutMe = "my name is " + firstName + " and my age is " + age //console.log(aboutMe) // Output: my name is harshit and my age is 22 //let firstName = 'harshit' //let age = 22 //let aboutMe = `my name is ${firstName} and my age is ${age}` //console.log(aboutMe) // Output : my bame is harshit and my age is 22 //// undefined //// null //// undefined //let firstName; //console.log(firstName) //console.log(firstName) //Output: undefined //var firstName; //console.log(firstName) // Output : undefined //const firstName; //console.log(firstName) //Output:index.js:512 //const firstName; SyntaxError: Missing initializer in const declaration //when you create variable but not asign value then it's show undefined // with the use of keyword let and var ,we don't asign value to variable its show undefined // but with const keyword we we don't asign any value to variable its show SyntaxError //let firstName; //console.log(firstName) //firstName = 'Harshit' //console.log(typeof firstName,firstName) // Output: undefined //string Harshit //// null //let myVariable = null; //console.log(typeof null) //console.log(myVariable) //myVariable = 'harshit' //console.log(myVariable,typeof myVariable) // Output : object // null // harshit string //console.log(typeof null) // Output: object // when we do typeof null it's show object instead of null it's bug // in the javascript it's bug or error ////BigInt //let myNumber = 123 //console.log(myNumber) //console.log(Number.MAX_SAFE_INTEGER) // Output:123 //9007199254740991 // in the javascript it's limit of number // if we want to use 9007199254740991 greater than this than we use BigInt //let myNumber =BigInt(123456789101112131415161718) //console.log(myNumber) // Output : 123456789101112138080976896n //let myNumber = 12345n //console.log(myNumber,typeof myNumber) // Output: 12345n BigInt //let myNumber = BigInt(12) //let sameNumber = 113n //console.log(myNumber + sameNumber) // Output: 125n //let myNumber = BigInt(12) //let sameNumber = 113 //console.log(myNumber+sameNumber) // Output: TypeError: Cannot mix BigInt and other types, use explicit conversions // both type should be same in BigInt //// boolean and comparison operator //// boolean // true , false //let num1 = 5 //let num2 = 7 //console.log(num1>num2) // Output: false //let num1 = 7 //let num2 = 7 //console.log(num1>num2) // Output: false //let num1 = 7 //let num2 = 7 //console.log(num1>=num2) // Output : true //let num1 = 9 //let num2 = 7 //console.log() //console.log(num1>num2) //console.log(num1<num2) // Output: true // false //let num1 = 6 //let num1 = 7 //console.log(num1<num2) // Output: true //// == vs === //// == //let num1 = 7 //let num2 = 7 //console.log(num1 == num2) // Output : true //let num1 = '7' //let num2 = 7 //console.log(num1 == num2) // Output: true // == meant for content comparison //let num1 = 9 //let num2 = 7 //console.log(num1 == num2) // Output: false //// === //let num1 = 7 //let num2 = 7 //console.log(num1 === num2) // Output : true //let num1 = '7' //let num2 = 7 //console.log(num1 === num2) // Output : false //// != vs !== //let num1 = 7 //let num2 = 7 //console.log(num1 != num2) // Output: false //let num1 = '7' //let num2 = 7 //console.log(num1 != num2) // Output : false //let num1 = 9 //let num2 = 7 //console.log(nu1 != num2) // Output: true //// !== //let num1 = 7 //let num2 = 7 //console.log(num1 !== num2) // Output : false //let num1 = '7' //let num2 = 7 //console.log(num1 !== num2) // Output : true //let num1 = 9 //let num2 = 7 //console.log(num1 !== num2) //Output : true //truthy and falsy values //falsy values //false //'' //null //undefined //0 //// if else condition //let age = 19; //if(age>18){ //console.log('user can play') //} // Output : user can play //let age = 17 //if(age>18){ //console.log('user can play') //}else{ //console.log("user can't play") //} // Output : user can't play //let num = 14 //if(num%2===0){ //console.log('even number') //}else{ //console.log('odd number') //} // Output: even number //falsy value // 1. false // 2. '' // 3. undefined // 4. null // 5. 0 // truthy value // 1. 'abc' // 2. 1,-1 //let firstName = '' //if(firstName){ //console.log(firstName) //}else{ //console.log('firstName kind a empty') //} // Output: firstName kind a empty //let firstName = false //if(firstName){ // console.log(firstName) //}else{ // console.log('firstName kind a empty') //} // Output: firstName kind a empty //let firstName = undefined //if(firstName){ //console.log(firstName) //}else{ //console.log('firstName kind a empty') //} // Output: firstName kind a empty //let firstName = null //if(firstName){ //console.log(firstName) //}else{ //console.log('firstName kind a empty') //} // Output: firstName kind a empty //let firstName = 0 //if(firstName){ //console.log(firstName) //}else{ // console.log('firstName kind a empty') //} // Output: firstName kind a empty //let firstName = 'harshit' //if(firstName){ //console.log(firstName) //}else{ // console.log('firstName kind a empty') //} // Output: harshit //let firstNumber = 1 //if(firstName){ //console.log(firstNumber) //}else{ //console.log('firstNumber kind a empty') //} // Output: 1 //// ternary operator //let age = 15; //let drink; //if(age>=5){ //drink='coffee' //}else{ // drink='milk' //} //console.log(drink) // Output: coffee // ternary operator / conditional operator //let age = 4; //let drink = age>=5 ?'coffee':'milk' //console.log(drink) // Output: milk //// and or operator //let firstName = 'harshit' //let age = 22 //if(firstName[0]==='h'){ //console.log('firstName start with h') //} // Output : firstName start with h //let firstName = 'harshit' //let age = 22 //if(age>18){ // console.log('your age is above 18') //} // Output : your age is above 18 // if you want to combine all above condition then use // and or operator // and or operator let firstName = 'harshit' let age = 22 if(firstName[0]==='h' && age > 18){ console.log('firstName start with h and your age above 18') } //const a1=['item1','item2','item3'] //const a2=[] //for(let i=0;i<a1.length;i++){ // a2.push(a1[i].toUpperCase()) // a2.push(a1[i]) //} //console.log(a2) //const fr = ['apple','mango','grapes']; //let i=0; //const f1=[] //while(i<fr.length){ //console.log(i) //console.log(fr[i].toUpperCase()) //f1.push(fr[i].toUpperCase()) //console.log(f1) //i++ //} //console.log(f1) //const fr=['apple','banana','mango'] //const fr2=[] //for(let f1 of fr){ // console.log(f1) //fr2.push(f1.toUpperCase()) //} //console.log(fr2) //const fr1=['apple','mango','grapes'] //const fr2=[] //for(let f1 in fr1){ //console.log(fr1[f1]) //fr2.push(fr1[f1]) //} //console.log(fr2) //destructing //const f1=['val1','val2','val3','val4'] //let [f2,f3,...f4]=f1 //console.log('value 1:',f2) //console.log('value 2:',f3) //console.log(f4) //let f5=[...f1] //console.log(f5) //object //const key = 'email' //let person={ //name:'bebu', //age:4, //hobbies:['sleeping','cartoon'] //} //person[key]='[email protected] ' //console.log(person) //console.log(person.hobbies) //console.log(person.hobbies[0]) //console.log(person) //console.log(person.key) //object //const person={ // name:'bebu', //age:4, //"person hobbies":['sleeping','cartoons'] //} //person.gender='female' //console.log(person) //for in loops //for(let key in person){ //console.log(key) //console.log(key,":",person[key]) //} //Object.keys //console.log(Object.keys(person)) //console.log(typeof(Object.keys(person))) //const val=Array.isArray(Object.keys(person)) //console.log(val) //for(let key of Object.keys(person)){ // console.log(key,":",person[key]) //} //computed properties //const key1='name' //const key2= 'nikename' //const val1 = 'disha' //const val2= 'bebu' //const obj={ //[key1]:val1, // [key2]:val2 //} //console.log(obj) //const obj={} //obj[key1]=val1, //obj[key2]=val2 //console.log(obj) // 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) //spread operator //const array1=[1,2,3] //const array2=array1.slice(0) //console.log(array2) //const a1=[1,2,3] //const a2=a1 //console.log(a1===a2)//true //console.log(array1===array2)//false //const array1=[1,2,3] //const array2=[4,5,6] //const array3=array1.slice(0).concat([7,8]) //console.log(array3)//[1,2,3,7,8] //const array3=[...array1,...array2,7,8,9] //console.log(array3) //const newarray=[..."abc"] //console.log(newarray)['a','b','c'] //const newarray1=[..."123456789"] //console.log(newarray1)//['1','2','3','4','5','6','7','8','9'] //spread operator in objects //const obj1={ //key1:'value1', //key2:'value2' //} //console.log(obj) //const obj2={ // key3:'value3', //key4:'value4' //} //const obj3={ ...obj1, ...obj2} //console.log(obj3)//{ key1: 'value1', key2: 'value2', key3: 'value3,key4:'value4' //const obj4={ //key1:'unquiekey', //key5:'value5', //key6:'value6' //} //const obj5={ ...obj4, ...obj1} //console.log(obj5)//{ key1: 'value1', key2: 'value2', key3: 'value3} //const obj6={ ...obj1, ...obj4} //console.log(obj6)//{ key1: 'unquiekey', key2: 'value2', key5: 'value5', key6: 'value6' } //const obj7={...obj1,...obj4,key69:'value69'} //console.log(obj7) //{ key1: 'unquiekey',key2: 'value2',key5: 'value5',key6: 'value6',key69: 'value69'} //const newa1={...'abc'} //console.log(newa1)//{ '0': 'a', '1': 'b', '2': 'c' } //const a2={...['item1','item2','item3']} //console.log(a2)//{ '0': 'item1', '1': 'item2', '2': 'item3' } //desturing in array //let a, b, rest; //[a, b] = [10, 20]; //console.log(a); // Expected output: 10 //console.log(b); // Expected output: 20 //[a, b, ...rest] = [10, 20, 30, 40, 50]; //console.log(rest); // Expected output: Array [30, 40, 50] //Desturing in objects //const band={ //bandname:'led Zeppelin', //bandsongs:'stairs for heaven', //year:1968, //anothersongs:'kashmir' //} //const bandname=band.bandname //const bandsongs=band.bandsongs //console.log(bandname,bandsongs)//led Zeppelin stairs for heaven //const {bandname:name,bandsongs:songs}=band //console.log(name,songs)//led Zeppelin stairs for heaven //let {bandname,bandsongs,...restprops}=band //console.log(bandname,bandsongs) //led Zeppelin stairs for heaven //console.log(restprops)//{ year: 1968, anothersongs: 'kashmir' } //Object inside Array //const users=[ //{userid:1,firstname:'harshit',gender:'male'}, //{userid:2,firstname:'mohit',gender:'male'}, //{userid:3,firstname:'nitish',gender:'male'} //] //console.log(user) //[{ userid: 1, firstname: 'harshit', gender: 'male' },{ userid: 2, firstname: 'mohit', gender: 'male' },{ userid: 3, firstname: 'nitish', gender: 'male' }] //for(let user of users){ //console.log(user) //} //output //{ userid: 1, firstname: 'harshit', gender: 'male' } //{ userid: 2, firstname: 'mohit', gender: 'male' } //{ userid: 3, firstname: 'nitish', gender: 'male' } //for(let user of users){ //console.log(user.userid)//123 //console.log(user.firstname)//harshit mohit nitish //console.log(user.gender)//male //} //Nested Desturing //const users=[ // {userid:1,firstname:'harshit',gender:'male'}, //{userid:2,firstname:'mohit',gender:'male'}, //{userid:3,firstname:'nitish',gender:'male'} //] //const [user1,user2,user3]=users //console.log(user1) //const [{firstname},,{gender}]=users //console.log(firstname,gender)//harshit male //change variable name in Desturing //const [{firstname:userfirstname,userid},,{gender:usergender}]=users //console.log(userfirstname)//harshit //console.log(userid)//1 //console.log(usergender)//gender //Function //Simple Function // function Declaration //function singHappyBirthday(){ //console.log('happy birthday to you...')// happy birthday to you //} //singHappyBirthday() //function sumTwoNumbers(Number1,Number2){ //return Number1+Number2 //} //const returnvalue=sumTwoNumbers(4,5) //console.log(returnvalue)//9 //const returnvalue1=sumTwoNumbers() //console.log(returnvalue1)//NaN //console.log(undefined+undefined)//NaN //function sumThreeNumbers(Number1,Number2,Number3){ //return Number1+Number2+Number3 //} //const returnvalue2=sumThreeNumbers(1,2,3); //console.log(returnvalue2)//6 //const returnvalue3=sumThreeNumbers(1,2) //console.log(returnvalue3)//NaN //iseven //function iseven(Number){ // if(Number%2===0){ //return true //}else{ //return false //} //} //console.log(iseven(5))//false //function iseven(number){ // if(number%2===0){ // return true //} //return false //} //console.log(iseven(2))// true //function iseven(number){ //return number%2===0 //} //console.log(iseven(2))//true //return first char index value //function firstChar(anystring){ //return anystring[0] //} //console.log(firstChar("abc"))//a // array from get target value place //function arrayTarget(array,target){ //for(let i=0;i<array.length;i++){ // if(array[i]===target){ // return i //} //} //return -1 //} //const array=[1,2,3,4,5] //console.log(arrayTarget(array,3))//2 //const array=[1,2,3,4,5] //console.log(arrayTarget(array,6))//-1 // function expression or Anonymous function // function expression means in one variable we assign function that's is called function expression //const singHappyBirthday=function(){ // console.log('happy birthday to you...') //} //singHappyBirthday()// happy birthday to you.. //const sumTwoNumbers=function(Number1,Number2){ //return Number1+Number2 //} //const returnvalue=sumTwoNumbers(4,5) //console.log(returnvalue)//9 //const isEven=function(number){ //return number %2===0 //} //console.log(isEven(2))//true //const firstChar=function(anystring){ //return anystring[0] //} //console.log(firstChar("abc"))//a //const arrayTarget=function(array,target){ //for(let i=0;i<array.length;i++){ // if(array[i]===target){ //return i //} //} //return -1 //} //const array=[1,2,3,4,5] //console.log(arrayTarget(array,3))//2 //essential //Arrow function //const singHappyBirthday=()=>{ // console.log('happy birthday to you...') //} //singHappyBirthday()//happy birthday to you... //const sumTwoNumbers=(Number1,Number2)=>{ // return Number1+Number2 //} //const returnvalue=sumTwoNumbers(4,5) //console.log(returnvalue)//9 //const isEven=(number)=>{ // return number %2===0 //} //console.log(isEven(2))//true //const isEven=(number)=>{ //return number %2===0 //} //console.log(isEven(2))//true //const firstChar=(anystring)=>{ //return anystring[0] //} //console.log(firstChar("abc"))//a //const arrayTarget=(array,target)=>{ //for(let i=0;i<array.length;i++){ //if(array[i]===target){ //return i //} //} //return -1 //} //const array=[1,2,3,4,5] //console.log(arrayTarget(array,3))//2 // remove curly braces in single arrow functions //const isEven=(number) => number % 2===0; //console.log(isEven(2))//true //firstChar=(anystring)=> anystring[0] //console.log(firstChar("abc"))//a //hoisting // hoisting is not work on expression(Anonymous) or arrow function // before declare variable we can access variable its show undefined,using var . if we can use const of let instead of var its show error //hello()// hello world //function hello(){ //console.log('Hello world') //} //console.log(hello)// undefiend //var hello='hello world' //console.log(hello)// hello world // in case we use let or const instead of var its throug error uncaught reference error // function inside function //function app(){ // const myFunc=()=>{ // console.log('Hello my Func') //} // const addTwo=(num1,num2)=>{ //return num1+num2 //} // const mulTwo=(num1,num2)=> num1*num2 //console.log('inside app') //myFunc()// hello my Func //console.log(addTwo(2,3))//5 // console.log(mulTwo(2,3))//6 //} //app()//inside app // using arrow function //const app1=()=>{ // const myFunc=()=>{ // console.log('Hello my Func') // } //const addTwo=(num1,num2)=>{ //return num1+num2 //} //const mulTwo=(num1,num2)=> num1*num2 //console.log('inside app') //myFunc()// hello my Func //console.log(addTwo(2,3))//5 //console.log(mulTwo(2,3))//6 //} //app1()//inside app //lexical scope //In JavaScript, a lexical environment is a data structure that stores all variables and function declarations. It allows the interpreter to recognize which variables or functions are accessible in different scopes within your program. //A lexical environment consists of two components: an environment record and a reference to the outer environment. //An environment record is an object that stores the variables and functions that are declared within the current lexical environment. //The reference to the outer environment is a pointer to the parent lexical environment, allowing the interpreter to access variables and functions defined in parent scopes. //JavaScript cares about the lexical environment when you ask for a variable while running a line of code inside any particular execution context if it can’t find that variable in its block it will go at the outer reference or block and look for variables there. //And that outer reference is where the function sits lexically is its outer environment. //So we can say that whenever a context ececution is created along with it a lexical enviroment is created and each lexical enviroment have referece to its parent lexical enviroments which points to its memory allocation. //function myapp(){ // const myVar='value1'; // function myFunc(){ // console.log('inside myfunc') //} //const myFunc2=function(){} //const myFunc3=()=>{} //console.log(myVar)//value1 //myFunc()//inside myfunc //} //myapp() //function myapp(){ // const myVar='value1'; // function myFunc(){ //const myVar='value59'; //console.log('inside myfunc',myVar) //} //const myFunc2=function(){} //const myFunc3=()=>{} // console.log(myVar)//value1 //myFunc()//inside myfunc value59 //} //myapp() //function myapp(){ //const myVar='value1'; //function myFunc(){ //const myVar='value59'; // here from remove myVar variable //javascript check our function scope it's myVar variable available or not ,if not available then goes to // lexical environment to check ,what is lexical environment myFunc where it's define inside myapp function then // myFunc its inside myapp that's why in the javascript myFunc is see on myapp function scope myVar variable is available // then it's print myvar variable value // console.log('inside myfunc',myVar) //} //const myFunc2=function(){} //const myFunc3=()=>{} //console.log(myVar)//value1 // myFunc()//inside myfunc value1 //} //myapp() //myVar='value1'; //we call or invoke myapp then we have to print myVar variable // first it will check inside myapp its myvar its their or not if not then // its check lexical environment means this function written on global environment // or global scope it's check on global myVar is available then it's print myVar . // now it's turn of myfunc function myVar is available on a myfuncf unction environment // or not if not then it's check lexical environment in myapp scope environment if it's not // then check on myapp lexical environment means myapp define in a global file or environment // then it's get myVar variable value1 //function myapp(){ // const myVar='value1'; // from here also we remove myVar varanasi //function myFunc(){ //const myVar='value59'; //here from remove myVar variable //javascript check our function scope it's myVar variable available or not ,if not available then goes to // lexical environment to check ,what is lexical environment myFunc where it's define inside myapp function then // myFunc its inside myapp that's why in the javascript myFunc is see on myapp function scope myVar variable is available // then it's print myvar variable value // console.log('inside myfunc',myVar) //} //const myFunc2=function(){} //const myFunc3=()=>{} //console.log(myVar)//value1 // myFunc()//inside myfunc value1 //} //myapp() //myVar='value1'; //we call or invoke myapp then we have to print myVar variable // first it will check inside myapp its myvar its their or not if not then // its check lexical environment means this function written on global environment // or global scope it's check on global myVar is available then it's print myVar . // now it's turn of myfunc function myVar is available on a myfuncf unction environment // or not if not then it's check lexical environment in myapp scope environment if it's not // then check on myapp lexical environment means myapp define in a global file or environment // then it's get myVar variable value1 //function myapp(){ // const myVar='value1'; // from here also we remove myVar varanasi //function myFunc(){ //const myVar='value59'; //here from remove myVar variable //javascript check our function scope it's myVar variable available or not ,if not available then goes to // lexical environment to check ,what is lexical environment myFunc where it's define inside myapp function then // myFunc its inside myapp that's why in the javascript myFunc is see on myapp function scope myVar variable is available // then it's print myvar variable value //const myFunc1=()=>{ //console.log('inside myfunc1',myVar) //} //myFunc1()//inside myfunc1 value1 //} //const myFunc2=function(){} //const myFunc3=()=>{} //console.log(myVar)//value1 //myFunc() //} //myapp() //Block scope vs function scope //{ //let firstName='harshit'; //} //console.log(firstName)// uncaught ReferenceError firstName is not defined //if any block have let and const using variable,but we can access let and const in that block only //we can't access variable out of block because of let and const used in that block //{ //let firstName='harshit'; // console.log(firstName)//harshit //now it's access because we console inside block //} //{ //let firstName='harshit'; //console.log(firstName)//harshit //} // we can use same name of variable for different different block using let and const variable //with different firstName value ,both variables are different block scope also have different //{ // let firstName='mohit'; //console.log(firstName)//mohit //} //{ // const firstName='harshit'; //} //console.log(firstName)//uncaught ReferenceError firstName is not defined //{ //const firstName='harshit'; //} //console.log(firstName)//uncaught ReferenceError firstName is not defined //{ // const firstName='mohit'; //} //console.log(firstName)// uncaught ReferenceError firstName is not defined //{ // const firstName='harshit'; //console.log(firstName)//harshit //} //{ // const firstName='mohit'; //console.log(firstName)//mohit //} //{ //const firstName='harshit'; //console.log(firstName)//harshit //} //{ //const firstName='mohit'; //console.log(firstName)//mohit //} // this block also have global block //const firstName ='garima'; //console.log(firstName)//garima //{ // var firstName='harshit'; //} //console.log(firstName)//harshit //in the case of var we can access variable outside of block //var is a function scope we can access variable outside of block //we can stated that whole file is main function when we can run javascript decodeURI //in the whole file we can use var and then access variable from anywhere //{ //var firstName='harshit'; //console.log(firstName)//harshit //} //{ // var firstName='mohit'; // console.log(firstName)//mohit //} //{ //var firstName='harshit'; //console.log(firstName)//harshit //} //{ //console.log(firstName)//mohit //} //{ // let firstName='harshit' // console.log(firstName);//harshit //} //{ // console.log(firstName);//uncaught ReferenceError firstName is not defined //} //whatever we write in {} it's called block //if(true){ //console.log('hello');//hello //} //if(true){ // let firstName='harshit'; //console.log(firstName)//harshit //} //console.log(firstName)//uncaught ReferenceError firstName is not defined //outside of block we can't access let or const variable its through error //function myApp(){ //if(true){ //let firstName='harshit'; // console.log(firstName)//harshit //} //console.log(firstName)//uncaught ReferenceError firstName is not defined //} //myApp() //we can't access let or const variable outside of block that's its show error //it's not get in their block then its look lexical environment //let firstName ='garima'; //function myApp(){ // if(true){ // let firstName ='harshit' //console.log('firstName')//harshit //} //console.log(firstName)//garima// now it's look lexical environment its not get function block then look global environment //} //myApp() //function myApp(){ // if(true){ // var firstName ='harshit' // console.log(firstName)// harshit //} //console.log(firstName)//harshit// var is access outside of block also any where in the block that's why it's harshit output //} //myApp() //function myApp(){ // if(true){ // var firstName ='harshit' //console.log(firstName)// harshit //} //if(true){ // console.log(firstName)//harshit //} //console.log(firstName)//harshit// var is access outside of block also any where in the block that's why it's harshit output //} //myApp() ////default parameter //simple function //function addTwo(a,b){ //return a+b //} //const ans=addTwo(4,5) //console.log(ans)//9 //function addTwo(a,b){ //return a+b; //} //const ans=addTwo(4) //console.log(ans)//NaN //function addTwo(a,b){ //if(typeof b ==="undefined"){ //b = 1; //} //return a+b; //} //const ans = addTwo(4); //console.log(ans);//5 //function addTwo(a,b){ // if(typeof b ==="undefined"){ // b = 0; //} // return a+b; //} //const ans = addTwo(4, 8); //console.log(ans);//12 //if b is not undefined then b value is now false then b's value not set 0 then b's value will be 12 now //function addTwo(a,b){ // if(typeof b ==="undefined"){ // b = 0; // } // return a+b; // } // default parameter b=0 //function addTwo(a,b=0){ //return a+b; //} //const ans = addTwo(4); //console.log(ans)//4 //function addTwo(a,b){ // if(typeof b ==="undefined"){ // b = 0; // } // return a+b; // } // default parameter b=0 not their now b value set 8 //function addTwo(a,b=0){ //return a+b; //} //const ans = addTwo(4,8); //console.log(ans)/12 //rest parameter //function myFunc(a,b,...c){ //console.log(`a is ${a}`);//a is 1 //console.log(`b is ${b}`);//b is 2 // console.log(`c is ${c}`);// c is 3,4,5,6,7 //console.log('c is',c)// c is [3,4,5,6,7] //} //myFunc(1,2,3,4,5,6,7) //function addall(...numbers){ // let total=0; // for(let number of numbers){ //total=total+number //} // return total //} //const ans = addall(1,2,3,4,5) //console.log(ans)//15 // parameter desturing // desturing work with objects // here person is objects //const person={ //firstName:'harshit', // gender:'male', //} //function printAllDetails(obj){ // console.log(obj.firstName);//harshit //console.log (obj.gender);//male //console.log(obj.age)//undefined //} //printAllDetails(person); //const person={ //firstName:'harshit', // gender:'male' //} // parameter desturing means we have to write curley brace inside using object value like firstName,gender //function printAllDetails({firstName,gender,age}){ //console.log(firstName);//harshit // console.log (gender);//male //console.log(age)//undefined //} //printAllDetails(person); // callback function //function myFunc(){ // console.log('hello world ');//hello world //} //myFunc() // we pass array in a //function myFunc(a){ //console.log(a)//[1,2,3,4,5] //console.log('hello world')//hello world //} //myFunc([1,2,3,4,5]) // we pass string in a //function myFunc(a){ //console.log(a)//abc // console.log('hello world ')//hello world //} //myFunc('abc') //function myFunc2(){ //console.log('inside my myFunc2') //} //function myFunc(callback){ // we call callback arguments as callback function inside myfunc // in myfunc we call function as input we expect and call then we say callback function //console.log('hello world')//hello world //callback()// inside my myFunc2 //} //myFunc(myFunc2) // we pass myFunc2 as parameter inside myfunc //function myFunc2(name){// then fifth harshit will be pass in name //console.log('inside my myFunc2')// then sixth inside my MyFunc2 print //console.log(`my name ${name}`)// here seventh my name is harshit print //} //function myFunc(callback){// then second myFunc2 pass here// here we state that high order function // we call callback arguments as callback function inside myfunc // in myfunc we call function as input we expect and call then we say callback function //console.log('hello world')//hello world // then third this line will run //callback('harshit')// inside my myFunc2 // then fourth callback run //} //myFunc(myFunc2)// first this we call // we pass myFunc2 as parameter inside myfunc //output // hello world // inside my myFunc2 // my name is harshit // function returning function // here we return string //function myfunc(){ //return 'a' //} //const ans=myfunc() //console.log(ans)// a is return // here we return array //function myfunc(){ // return [1,2,3]; //} //const ans=myfunc() //console.log(ans)// we return array is [1,2,3] // here we return object //function myfunc(){ //return {name:'harshit',age:22}; //} //const ans=myfunc() //console.log(ans)// we retuageobject is {name: 'harshit',age:22} // here we return number //function myfunc(){ // return 1; //} //const ans=myfunc() //console.log(ans)// we return number is 1 //function myFunc(){ //function hello(){ //console.log('hello world') //} //return hello; //} //const ans=myFunc() //console.log(ans)// here we print function when return hello in ans output is [Function: hello] //here we call function ans() //function myFunc(){ //function hello(){ //console.log('hello world') //}// here is a function which is return another function name is hello //return hello; //} //const ans=myFunc()// hello will be return and store in variable ans and now that ans variable will function call that ans() now we stated that function returning function //ans()// here we call function print hello world // we call high order function //here we call function ans() and print //function myFunc(){ //function hello(){ //return hello world' //}// here is a function which is return another function name is hello //return hello; //} //const ans=myFunc()// hello will be return and store in variable ans and now that ans variable will function call that ans() now we stated that function returning function //console.log(ans())// here we call function print function output is hello world //here we call function ans() //function myFunc(){ //return function(){ //return 'hello world' // }; //} //const ans=myFunc()// hello will be return and store in variable ans and now that ans variable will function call that ans() now we stated that function returning function //console.log(ans())// here we call function print hello world //important or crucial array methods //1.forEach //2.map (is curcial) //3.filter //4.reduce //const numbers=[4,2,5,8] //function multiplyby2(number,index){ //console.log('index is',index) //console.log(`${number}*2=${number*2}`) //} //multiplyby2(numbers[0],0)// here we have to write again for all arrays elements then we have use for loop //Output: //index is 0 //4*2=8 //using traditional for loops //const numbers=[4,2,5,8] //function multiplyby2(number,index){ //console.log('index is',index) //console.log(`${number}*2=${number*2}`) //} //for(let i=0;i<numbers.length;i++){ // multiplyby2(numbers[i],i) //} //Output: //index is 0 //4*2=8 //index is 1 //2*2=4 //index is 2 //5*2=10 //index is 3 //8*2=16 //const numbers=[4,2,5,8] //function myfunc(number,index){ //console.log(`index is ${index} and value is ${number}`) //} //for(let i=0;i<numbers.length;i++){ //myfunc(numbers[i],i) //} //Output: //index is 0 value is 4 //index is 1 value is 2 //index is 2 value is 5 //index is 3 value is 8 //Callback function //A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. //1.forEach //const numbers=[4,2,5,8] //function myfunc(number,index){ //console.log(`index is ${index} value is ${number}`) //} //numbers.forEach(myfunc)// forEach take a function or (callback) as input here input is myfunc and forEach pass both arguments number and index from array // numbers is variable as array forEach is used // forEach pass both arguments by self we don't pass both arguments its take function and pass arguments //forEach work as traditional for loops //Output: //index is 0 value is 4 //index is 1 value is 2 //index is 2 value is 5 //index is 3 value is 8 // forEach using anamous functions means functions don't have name //const numbers= [4,2,5,8] //numbers.forEach(function(number,index){ //console.log(`index is ${index} value is ${number}`) //}); //forEach never give new array that's we take console.log here instead return //here function we don't give their name that's we state that anamous function // function here take parameter as number and index // forEach here pass arguments number and index to parameter // function(number,index) is function // forEach (function(number, index)) take callback function, forEach call for every elements and index for themselves first time iterate and print number //Output //index is 0 value is 4 //index is 1 value is 2 //index is 2 value is 5 //index is 3 value is 8 // forEach using anamous functions multiply with 2 //const numbers= [4,2,5,8] //numbers.forEach(function(number){ //console.log(` Number is ${number*2}`) //}); //forEach whenever call pass index also //Output: // Number is 8 //Number is 4 //Number is 10 //Number is 16 //forEach using array with object //const users=[ // {firstname:'harshit',age:23}, // {firstname:'mohit',age:21}, //{firstname:'nitish',age:22}, //{firstname:'garima',age:20}, // ]; //users.forEach(function(user){// anamous function //console.log(user.firstname ) //}) //Output: //harshit //mohit //nitish //garima //without using forEach with for of //const users=[ //{firstname:'harshit',age:23}, //{firstname:'mohit',age:21}, //{firstname:'nitish',age:22}, //{firstname:'garima',age:20}, //]; //for(let user of users){ // console.log(user.firstname) //} //Output: //harshit //mohit //nitish //garima // using traditional for loops //for(let i=0;i<users.length;i++){ //console.log(users.firstname) //} //Output: //harshit //mohit //nitish //garima // forEach using arrow function //const users=[ //{firstname:'harshit',age:23}, //{firstname:'mohit',age:21}, //{firstname:'nitish',age:22}, //{firstname:'garima',age:20}, //]; //users.forEach((user,index)=>{ //console.log(user.firstname,index) //}) //Output: //harshit o //mohit 1 //nitish 2 //garima 3 //map method (crucial method) //const numbers=[3,4,6,1,8] //const squares=function(number){// here we taken function expression //return number*number //} //const squareNumber= numbers.map(squares) //console.log(squareNumber) // numbers we used map method // map method take input as callback function //map method take one element from array return that array in new array form // map return new array // map return new array that's why we store in new variable name is squareNumber //Output [ 9, 16, 36, 1, 64 ] //const numbers=[3,4,6,1,8] //const squares=function(number){// here we taken function expression //console.log(number*number) //} // it's crucial whenever use map method return elements instead using console.log // if we not used return then in function then return is undefined because it's return something if we store in any variable then show undefined //const squareNumber= numbers.map(squares) //console.log(squareNumber) //Output //9 //16 //36 //1 //64 //[ undefined, undefined, undefined, undefined, undefined ] //const numbers=[3,4,6,1,8] //const squareNumber=numbers.map(function(number){// map method used with anamous function //return number*number //}) //console.log(squareNumber) //Output: //[ 9, 16, 36, 1, 64 ] //const numbers=[3,4,6,1,8] //const squareNumber=numbers.map((number)=>{ // map method using arrow function //return number*number //}) //console.log(squareNumber) //Output: //[ 9, 16, 36, 1, 64 ] //const numbers=[3,4,6,1,8] //const squareNumber=numbers.map((number,index)=>{ // map method using arrow function //return (`index:${index},${number*number}`) //}) //console.log(squareNumber) //Output: //[ 'index:0,9', 'index:1,16', 'index:2,36', 'index:3,1', 'index:4,64'] // map method with array in object //const users=[ //{firstname:'harshit',age:23}, // {firstname:'mohit',age:21}, //{firstname:'nitish',age:22}, //{firstname:'garima',age:20} //] //const userfirstname=users.map((user)=>{// here we pass arrow function in map method and using object firstname and its return new array we store in userfirstname variable //return user.firstname //}) //console.log(userfirstname) // Output:[ 'harshit', 'mohit', 'nitish', 'garima' ] // filter method // filter function using function expression //const numbers=[1,3,2,6,4,8] //const isEven=function(number){ //return number%2===0; //} // here we taken function expression // filter method take a input as callback function // filter callback function always return boolean value either True or False // filter function pass 1 from numbers in iseven function, 1 is odd number if reminder not come 0 then filter function not added in new array because it's odd numbers // filter function return True added value in new array which is created by filter // return value stored in new variable and print that variable // filter function callback function slways return True or False //const evenNumbers =numbers.filter(isEven) //console.log(evenNumbers) //Output: [ 2, 6, 4, 8 ] // filter function using arrow function //const numbers=[1,3,2,4,6,8] //const evenNumbers =numbers.filter((number)=>{ //return number%2===0; //}); //console.log(evenNumbers); //Output: [ 2, 6, 4, 8 ] //const numbers=[1,3,2,4,6,8] //const isoddNumbers=numbers.filter((number)=>{ // return number%2!==0; //}); //console.log(isoddNumbers); //Output:[ 1, 3 ] // reduce method // reduce method using arrow function //const numbers=[1,2,3,4,5,10] //const sum=numbers.reduce((accumlator,currentValue)=>{ //return accumlator + currentValue; //}) //console.log(sum) // Output: 25 // reduce method first parameter is accumlator and second parameter is currentValue // accumlator take 1 as arguments from numbers array and currentValue take 2 as arguments from numbers array and then add return as 3 // now that return value become accumlator value 3 and currentValue take 3 as arguments from numbers array and then add return as 6 // again that return value become accumlator value 6 and currentValue take 4 as arguments from numbers array and then add return as 10 // now also return value become accumlator value 10 and currentValue take 5 as arguments from numbers array and then return as 15 // now return value become accumlator value 15 and currentValue take 10 as arguments from numbers array and then return as 25 // now this return value 25 stored in sum variable and console.log // reduce do from numbers array give sum // accumlator + currentValue return // 1 2 3 // 3 3 6 // 6 4 10 // 10 5 15 // 15 10 25 // reduce method using arrow function //const numbers=[1,2,3,4,5,10] //const sum=numbers.reduce((accumlator,currentValue)=>{ //return accumlator + currentValue; //},100) //console.log(sum) // Output: 125 // reduce method use arrow function ,where arrow function is end we take initial value to pass parameter first value to accumlator // reduce method first parameter is accumlator and second parameter is currentValue // accumlator take 100 as arguments from initial value and currentValue take 1 as arguments from numbers array and then add return as 101 // now that return value become accumlator value 101 and currentValue take 2 as arguments from numbers array and then add return as 103 // again that return value become accumlator value 103 and currentValue take 3 as arguments from numbers array and then add return as 106 // now also return value become accumlator value 106 and currentValue take 4 as arguments from numbers array and then return as 110 // now return value become accumlator value 110 and currentValue take 5 as arguments from numbers array and then return as 115 //now return value become accumlator value 115 and currentValue take 10 as arguments from numbers array and then return as 125 // now this return become 125 stored in sum variable and console.log // reduce do from numbers array give sum // accumlator + currentValue return // 1 2 3 // 3 3 6 // 6 4 10 // 10 5 15 // 15 10 25 // array inside object used in reduce method //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); //console.log(totalAmount) //we using obect in array then we to access obect from array then we use currentProduct.price //Output: 49000 // forEach,map,filter and reduce not change original array its ForEach not return any thing but not change original array // map not change original array but return new array filter also not change original array but return True or False array // reduce also not change original array but not return any array //sort method //ascii //Char ASCII code //NULL 00 //SOH 01 //STX 02 //ETX 03 //EOT 04 //ENQ 05 //ACK 06 //BEL 07 //BS 08 //HT 09 //LF 10 //VT 11 //FF 12 //CR 13 //SO 14 //SI 15 //DLE 16 //DC1 17 //DC2 18 //DC3 19 //DC4 20 //NAK 21 //SYN 22 //ETB 23 //CAN 24 //EM 25 //SUB 26 //ESC 27 //FS 28 //GS 29 //RS 30 //US 31 //DEL 127 //! 33 //“ 34 //# 35 //$ 36 //% 37 //& 38 //‘ 39 //( 40 //) 41 //* 42 //+ 43 //, 44 //– 45 //. 46 /// 47 //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 //~ 126 // sort method change the original array or muted the original array //const numbers=[5,9,1200,410,3000] //numbers.sort() //console.log(numbers) // Output: [1200,3000,410,5,9] // javascript sort in string ['5','9','410','1200','3000'] then convert in number // javascript sort on ascii from their number [53,57,52,49,51] // now javascript sort at [49,51,52,53,57] // in the javascript array in that is not numbers its string // in the javascript sort method use on array its string not number,it's means its sort on sting as their value on ascii code // ascii code 1 is 49, 3 is 51,4 is 52 ,5 is 53, 9 is 57 // in this way sorted not from number to sort // javascript look on 1 give their ascii code and 3 also some as other sting number also do // sort method change string on ascii code then change number in sort method //const usersNames = ['harshit','abcd','mohit','nitish'] //usersNamesrt() //console.log(usersNames) //Output:[ 'abcd', 'harshit', 'mohit', 'nitish'] // sort method used on string array its sort like dictionary form // ascii code a is 97,h is 104 ,m is 109, n is 110 its sort //const usersNames= ['harshit','abcd','mohit','nitish','aabc'] //usersNames.sort() //console.log(usersNames) //Output:[ 'aabc', 'abcd', 'harshit', 'mohit', 'nitish'] //const usersNames = ['harshit','abcd','mohit','nitish','aabcd','ABC','HARSHIT'] //usersNames.sort() //console.log(usersNames) //Output: ['ABC','HARSHIT','aabcd','abcd','harshit', 'mohit','nitish'] // ascii code first take small ascii value which is capital alphabets value is A is 65 and H is for 72,small alphabets value is a is 97 // first sort in ascii value capital alphabets then second sort on small alphabets ascii value sort // then its convert on ascending order // sort in ascending order //const numbers=[5,9,1200,410,3000] //numbers.sort((a,b)=>{ //return a-b //}) //console.log(numbers) // 1200,410 //1200-410= 790 //a-b = positive (greater than 0) b,a // 410,1200 // if a value is greater than b then we exchange numbers postion first b then a // 5,9 // 5-9 =-4 // a-b = negative(smaller than 0) a,b // 5,9 // if a value is smaller than b we keep theor value as its first a then b // sort descending order numbers = [5,9,1200,410,3000] numbers.sort((a,b)=>{ return b-a }) console.log(numbers)
Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.
Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log("Hello, " + line);
});
Keyword | Description | Scope |
---|---|---|
var | Var is used to declare variables(old way of declaring variables) | Function or global scope |
let | let is also used to declare variables(new way) | Global or block Scope |
const | const is used to declare const values. Once the value is assigned, it can not be modified | Global or block Scope |
let greetings = `Hello ${name}`
const msg = `
hello
world!
`
An array is a collection of items or values.
let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);
let mobiles = ["iPhone", "Samsung", "Pixel"];
// accessing an array
console.log(mobiles[0]);
// changing an array element
mobiles[3] = "Nokia";
Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.
() => expression
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
.map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);
let [firstName, lastName] = ['Foo', 'Bar']
let {firstName, lastName} = {
firstName: 'Foo',
lastName: 'Bar'
}
const {
title,
firstName,
lastName,
...rest
} = record;
//Object spread
const post = {
...options,
type: "new"
}
//array spread
const users = [
...adminUsers,
...normalUsers
]
function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
console.log(`Hello ${name}!`);
}
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar
IF is used to execute a block of code based on a condition.
if(condition){
// code
}
Else part is used to execute the block of code when the condition fails.
if(condition){
// code
} else {
// code
}
Switch is used to replace nested If-Else statements.
switch(condition){
case 'value1' :
//code
[break;]
case 'value2' :
//code
[break;]
.......
default :
//code
[break;]
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while (condition) {
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.
class className {
constructor() { ... } //Mandatory Class method
method1() { ... }
method2() { ... }
...
}
class Mobile {
constructor(model) {
this.name = model;
}
}
mbl = new Mobile("iPhone");