ECMAScript 6 introduced the let statement.

I've heard that it's described as a local variable, but I'm still not quite sure how it behaves differently than the var keyword.

What are the differences?. When should let be used instead of var?

javascript scope ecmascript-6 var let 

Nov 17

6 Answers

Scoping rules

The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).

function run() {
  var foo = "Foo";
  let bar = "Bar";

  console.log(foo, bar); // Foo Bar

  {
    var moo = "Mooo"
    let baz = "Bazz";
    console.log(moo, baz); // Mooo Bazz
  }

  console.log(moo); // Mooo
  console.log(baz); // ReferenceError
}

run();

The reason why let the keyword was introduced to the language was function scope is confusing and was one of the main sources of bugs in JavaScript.

Take a look at this example from another Stack Overflow question:

var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
  // and store them in funcs
  funcs[i] = function() {
    // each should log its value.
    console.log("My value: " + i);
  };
}
for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcs[j]();
}

My value: 3 was output to console each time funcs[j](); was invoked since anonymous functions were bound to the same variable.

People had to create immediately invoked functions to capture correct values from the loops but that was also hairy.

Hoisting

While variables declared with var keywords are hoisted (initialized with undefined before the code is run) which means they are accessible in their enclosing scope even before they are declared:

function run() {
  console.log(foo); // undefined
  var foo = "Foo";
  console.log(foo); // Foo
}

run();

let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. The variable is said to be in the "temporal dead zone" from the start of the block until the initialization is processed.

function checkHoisting() {
  console.log(foo); // ReferenceError
  let foo = "Foo";
  console.log(foo); // Foo
}

checkHoisting();

Creating global object property

At the top level, let, unlike var, does not create a property on the global object:

var foo = "Foo";  // globally scoped
let bar = "Bar"; // not allowed to be globally scoped

console.log(window.foo); // Foo
console.log(window.bar); // undefined

Redeclaration

In strict mode, var will let you re-declare the same variable in the same scope while let raises a SyntaxError.

'use strict';
var foo = "foo1";
var foo = "foo2"; // No problem, 'foo1' is replaced with 'foo2'.

let bar = "bar1"; 
let bar = "bar2"; // SyntaxError: Identifier 'bar' has already been declared

answered Dec 31


I think it is some kind of very confusing mistake there:

The var keyword is used in pre-ES6 versions of JS.
let is the preferred way to declare a variable when it can be reassigned,

Actually, it is not true about the difference between let and var.
There’s a difference in scope, but not in reassignment. Reassigned could be variables declared by any non-const keyword. That’s the definition of the variable. It can be reassigned by using the assignment operator.

If they meant redeclared, it works only in strict mode and is just the polar opposite.

Redeclaration:
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not:
‘use strict’;
let me = ‘foo’;
let me = ‘bar’; // SyntaxError: Identifier ‘me’ has already been declared
‘use strict’;
var me = ‘foo’;
var me = ‘bar’; // No problem, me is replaced.

answered Dec 31


Is it safe to use let today?

Some people would argue that in the future we'll ONLY use let statements and that var statements will become obsolete. JavaScript guru Kyle Simpson wrote a very elaborate article on why he believes that won't be the case.

Today, however, that is definitely not the case. In fact, we need actually to ask ourselves whether it's safe to use the let statement. The answer to that question depends on your environment:

If you're writing server-side JavaScript code (Node.js), you can safely use the let statement.

If you're writing client-side JavaScript code and use a browser-based transpiler (like Traceur or babel-standalone), you can safely use the let the statement, however, your code is likely to be anything but optimal with respect to performance.

If you're writing client-side JavaScript code and use a Node-based transpiler (like the traceur shell script or Babel), you can safely use the let statement. And because your browser will only know about the transpired code, performance drawbacks should be limited.

If you're writing client-side JavaScript code and don't use a transpiler, you need to consider browser support.

There are still some browsers that don't support let at all :

answered Dec 31


Difference Between var and let in JavaScript

Here is a list of the differences between var and let in JavaScript.

Iterations in JavaScript

Var: This keyword got introduced along with JavaScript.
Let: This keyword was added in the ES 2015 (ES6) version of JavaScript.

Scope

Var: The var keyword has a global scope.
Let: The let keyword stays limited to the block scope.

Access and Declaration

Var: One can easily declare as well as access it globally.
Let: One can easily declare it globally but can’t access it globally.

Redeclaration

Var: We can re-declare any variable that we declare using the var keyword, and we can also update it in the very same scope.
Let: We can upload any variable that we declare using the let keyword but not re-declare it in the very same scope.
 

answered Dec 31


var

Variables in TypeScript can be declared using the var keyword, same as in JavaScript. The scoping rules remain the same as in JavaScript.

let

To solve problems with var declarations, ES6 introduced two new types of variable declarations in JavaScript, using the keywords let and const. TypeScript, being a superset of JavaScript, also supports these new types of variable declarations.

answered Dec 31


Difference between var, let, const in Javascript

From ES6 we have three ways to declare a variables
var a = 48; const b = 'Hello Shaik'; let c = true; The type of declaration depends on the scope. The scope is the fundamental concept in all programming languages that defines the visibility of a variable.
 

Var

 The var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Ex:

function testVar() {
  	var x = 1;
  	if (true) {
    	var x = 2;  // same variable
    	console.log(x);  // 2
  	}
  	console.log(x);  // 2
}

let

let allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used. 

if you run the below code it will throw an error

if (true) {
  	let name = 'Hi Shaik';
}
alert(name); //generates an error 

In this above case, the name variable is accessible only in the scope of the if statement because it was declared as let.

Ex:

function letTest() {
  	let x = 1;
  	if (true) {
    	let x = 2;  // different variable
    	console.log(x);  // 2
  	}
  	console.log(x);  // 1
}

answered Dec 31


Login and Submit Your Answer
Browse other questions tagged  javascript  scope  ecmascript-6  var  let or ask your own question.