Scope level and mini hoisting
Global and local scope
let a = 10
const b = 20
Var c = 30
console.log(a)
console.log(b)
console.log(c)
- If var is working then why let and const?
\=> Because var doesn’t work in block scope.
{ } => scope when it comes with a conditional statement or loop or function
If(true){
let a =10;
const b = 20;
Var c = 30;
}
console.log(a) // this will give error
console.log(b) // this will also give error
console.log(c); // this will print 30 and
//this is the problem and thus starts the concept of
//scope and we should avoid using "var"
let a = 300; //global scope
If(true){
let a = 30; // block scope
console.log(a); // this will print 30
}
console.log(a) // this will print 300
function one (){
const username = "harsh"
function two (){
const web = "yt"
console.log(username) //this will give no error as child function can access variables of parent function.
}
console. log(website) //error as website not defined
two()
}
one()
// Child function can access variables of parent function but parent function can't access variables of child function.
Concept of hoisting in brief:-
addOne(num) // if I call function here it will still work because of the way it has been initialized .
function addOne(num){
return num + 1;
}
addTwo() // this will give error as not initialized because of the way function has been initialized.
const addTwo = function(num){
return num + 2;
}
addTwo () // it must be called after initializing.