xxxxxxxxxx
Function scope is within the function.
Block scope is within curly brackets.
var character4 =
function foo() {
if(true) {
var character1 = "Robin" //function scope
let character2 = "Ted" //block scope
const character3 = "Barney" //block scope
}
console.log(character1) //Robin
console.log(character2) //not defined
console.log(character3). //not defined
}
xxxxxxxxxx
//let
1. It's used in block-scoped.
2. It does not allow to redeclare variables.
3. Hoisting does not occur in let.
// var
1. It's used in function scoped.
2. It allows to redeclare variables.
3. Hoisting occurs in var.
xxxxxxxxxx
var is function scoped and let is block scoped. Let's say you have:
function understanding_var() {
if (1 == 1) {
var x = 5;
console.log('the value of x inside the if statement is ' + x);
}
console.log(x);
}
//output: the value of x inside the if statement is 5
5
function understanding_let() {
if (1 == 1) {
let x = 5;
console.log('the value of x inside the if statement is ' + x);
}
console.log(x);
}
//output: the value of x inside the if statement is 5
Uncaught ReferenceError: x is not defined
var is defined throughout the entire function, even if it's inside the if
statement, but the scope of let is always within the curly braces, not outside
it, even if the conditional statement is inside the function.
xxxxxxxxxx
let: //only available inside the scope it's declared, like in "for" loop,
var: //accessed outside the loop "for"
xxxxxxxxxx
function run() {
var foo = "Foo";
let bar = "Bar";
console.log(foo, bar);
{
let baz = "Bazz";
console.log(baz);
}
console.log(baz); // ReferenceError
}
run();
xxxxxxxxxx
let = 10 // accessable only in defined scope
var = 10 // accessable in the function it is declared in (global variable in a function)
xxxxxxxxxx
/* DIFFERENCE BETWEEN LET AND VAR */
//LET EXAMPLE
{
let a = 123;
};
console.log(a); // undefined
//VAR EXAMPLE
{
var a = 123;
};
console.log(a); // 123