javascript let vs var code example
Example 1: javascript var let
function func(){
if(true){
var A = 1;
let B = 2;
}
A++;
B++;
return A + B;
}
Example 2: var vs let js
let:
var:
Example 3: difference between var and let
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);
}
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);
}
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.
Example 4: let in javascript
The let statement declares a block scope local variable, optionally initializing it to a value.
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
}
console.log(x);
Example 5: let and var difference
function run() {
var foo = "Foo";
let bar = "Bar";
console.log(foo, bar);
{
let baz = "Bazz";
console.log(baz);
}
console.log(baz);
}
run();
Example 6: let javascript
var i = "global";
function foo() {
var i = "local";
console.log(i);
}
foo();
console.log(i);