0
Q:

let vs var javascript

// var has function scope.
// let has block scope.

function func(){
  if(true){
    var A = 1;
    let B = 2;
  }
  A++; // 2 --> ok, inside function scope
  B++; // B is not defined --> not ok, outside of block scope
  return A + B; // NaN --> B is not defined
}
4
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.
2
let: //only available inside the scope it's declared, like in "for" loop, 
var: //accessed outside the loop "for"
7
Input:
console.log(x);
var x=5;
console.log(x);
Output:
undefined
5

var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped.
It can be said that a variable declared with var is defined throughout the program as compared to let.
3
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);
  // expected output: 2
}

console.log(x);
// expected output: 1
8
Input:
console.log(x);
let x=5;
console.log(x);
Output:
Error
2
var: older
let: newer
0
let /*Var name*/ = /*what is equals*/
0

New to Communities?

Join the community