Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using "let" and "var"?

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?

like image 714
TM. Avatar asked Apr 17 '09 20:04

TM.


People also ask

Is it better to use let or VAR?

This is because both instances are treated as different variables since they have different scopes. This fact makes let a better choice than var . When using let , you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.

What is the difference between VAR & let?

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. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.

Which is faster VAR or let?

In terms of performance comparison, var is faster and let is slower inside the loops while running or executing the code. Re-declaring var declared a variable in the same function or scope gives rise to Syntax Error whereas let declared variable cannot be redeclared.

What is the difference between LET and Var and const?

Introduction to the Difference Between Var, Let, and Const Here if we will declare a var variable or let variable, then it can be updated, but if we declare a const variable, it will not be updated in any case and will work fine with our function.


2 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 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 keyword 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 "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
like image 183
38 revs, 28 users 27% Avatar answered Oct 19 '22 12:10

38 revs, 28 users 27%


let can also be used to avoid problems with closures. It binds fresh value rather than keeping an old reference as shown in examples below.

for(var i=1; i<6; i++) {    $("#div" + i).click(function () { console.log(i); });  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <p>Clicking on each number will log to console:</p>   <div id="div1">1</div>  <div id="div2">2</div>  <div id="div3">3</div>  <div id="div4">4</div>  <div id="div5">5</div>

Code above demonstrates a classic JavaScript closure problem. Reference to the i variable is being stored in the click handler closure, rather than the actual value of i.

Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click.

A general workaround is to wrap this in an anonymous function and pass i as an argument. Such issues can also be avoided now by using let instead var as shown in the code below.

(Tested in Chrome and Firefox 50)

for(let i=1; i<6; i++) {    $("#div" + i).click(function () { console.log(i); });  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <p>Clicking on each number will log to console:</p>   <div id="div1">1</div>  <div id="div2">2</div>  <div id="div3">3</div>  <div id="div4">4</div>  <div id="div5">5</div>
like image 26
Gurpreet Singh Avatar answered Oct 19 '22 13:10

Gurpreet Singh