Answers for "let vs var"

19

var vs let js

let: //only available inside the scope it's declared, like in "for" loop, 
var: //accessed outside the loop "for"
Posted by: Guest on May-22-2020
4

const let var scope

var num = 1;   //var can be function or global scoped
const num = 2; //const can only be block scoped
let num = 3;   //let can only be block scoped
Posted by: Guest on December-19-2020
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
12

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);
  // expected output: 2
}

console.log(x);
// expected output: 1
Posted by: Guest on April-02-2020
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

Browse Popular Code Answers by Language