Answers for "difference between "let" and "var"?"

10

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);
} 
//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.
Posted by: Guest on November-27-2020
4

difference between "let" and "var"?

In simple words 'var' is function scoped and 'let' is block scoped
Posted by: Guest on October-02-2021
3

Difference between let and var in javascript

let a = 'hello'; // globally scoped
var b = 'world'; // globally scoped
console.log(window.a); // undefined
console.log(window.b); // 'world'
var a = 'hello';
var a = 'world'; // No problem, 'hello' is replaced.
let b = 'hello';
let b = 'world'; // SyntaxError: Identifier 'b' has already been declared
Posted by: Guest on May-22-2021
2

let vs var

// var is function-scoped, so redeclaring it in a block will cause its value outside the block to change as well:

var one = 'one: declared outside the block';

if (true === true) {
  var one = 'one: declared inside the block'; // notice: we redeclare 'one' here
  console.log(one); // prints 'one: declared inside the block'
}

console.log(one); // also prints 'one: declared inside the block', because the variable was redeclared in the 'if' block. The outer 'var' variable was therefore destroyed and replaced by inner var variable.

// 'let' is block-scoped, so redeclaring a 'let' variable inside of a block creates a different 'let' variable with the same name whose scope is inside the block:

let two = 'two: declared outside the block';

if (true === true) {
  let two = 'two: declared inside the block';
  console.log(two); // prints 'two: declared inside the block'
}

console.log(two); // prints 'two: declared outside the block', because two declared inside the block is a separate variable. The 'let' variables are unrelated and therefore are unaffected by each other.
Posted by: Guest on July-13-2021

Code answers related to "difference between "let" and "var"?"

Code answers related to "Javascript"

Browse Popular Code Answers by Language