Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Var vs. Let in JavaScript

DZone 's Guide to

Var vs. Let in JavaScript

We take a look into the reasons why let has replaced var as the way to declare variables in JavaScript.

· Web Dev Zone ·
Free Resource

In this article, we wil be discussing the long running debate of var vs. let in JavaScript. We will also be discussing why the use of let is increasing in dev communities.

Var vs Let in JavaScript | Full Stack Geek

Var vs Let in JavaScript

Introduction

Declaring variables in JavaScript was not a cake walk until 2015 when ECMA 2015 was introduced and hence let and const was introduced and we got rid of var (it still works though!).

Why I have used the phrase, "got rid of"? Imagine you are allowed to declare variables again and again within the same scope (which is allowed when you are using var and obviously not allowed in case of let). This would lead to a mess as your code base would grow significantly and hence let was introduced to throw an error if you ever try to re-declare a variable within the same scope.

In this article, we would be discussing such anomalies with using var in-depth.

Why let Is Superior to var

Now, we will be discussing in-depth why let is considered to be far superior to var when it comes to the declaration of variables.

Declaring Variables With the Same Name and Within the Same Scope

Consider that you are using the old method of declaring variables in JavaScript, i.e, you are using var instead of let. Hence, you are allowed to do this:

var name = 'abc';  
console.log(name);  
name = 'def';  
console.log(name);  
var name = 'ghe';  
console.log(name);

Here, you can clearly see that we have re-declared a variable named "name" within the same scope and JavaScript will not throw any error whatsoever and this makes var so scary because as your code base grows, it will become difficult to keep your code manageable.

On the other hand, if you use "let" for the same, JavaScript will not allow you to do this and you will be immediately notified that you have already declared that variable earlier in the same scope and hence you will be saved from overwriting a variable's value. For example, if you try to do something like:

let name = 'abc';  
console.log(name);  
name = 'def';  
console.log(name);  
let name = 'ghe';

Upon execution, JavaScript would throw an error similar to this:

let name = 'ghe';  
   ^  
 SyntaxError: Identifier 'name' has already been declared  
   at createScript (vm.js:80:10)  
   at Object.runInThisContext (vm.js:139:10)  
   at Module._compile (module.js:616:28)  
   at Object.Module._extensions..js (module.js:663:10)  
   at Module.load (module.js:565:32)  
   at tryModuleLoad (module.js:505:12)  
   at Function.Module._load (module.js:497:3)  
   at Function.Module.runMain (module.js:693:10)  
   at startup (bootstrap_node.js:188:16)  
   at bootstrap_node.js:609:3  

var Is Function-Scoped While let Is Block-Scoped

Var is function-scoped and not block-scoped, which means that constructs like if statements, while loops, etc. do not create new scopes while using var. It also means that, as var is function-scoped, if we do not create a function then we do not create a new scope while using var and, hence, it will make our life hell. Why?

Suppose you want to use a local variable inside a for loop and want it to get reset once the execution of the for loop completes.

If you have used var to declare the variable inside the for loop, it will not reset that variable even after execution of the for loop as, except for functions, nothing will create a new scope for variables declared with var. On the other hand, let is block-scoped, so it will create a new scope for the local variable as soon as a new for loop (or any other construct like if statements, while loops, switch cases, functions, and so on) starts.

Consider the code snippets for both the cases by clicking on the following links and see the code in action:

Variables Are Accessible Even Before Their Declaration

Yes, you read that right! Using var causes such a mess that you can actually use the variables even before defining them. Actually, what happens is, whenever you declare a variable with var, it's declaration gets hoisted to the top and hence it seems as if the variable is already declared even before it was actually declared. Consider the following code:

document.write(name);
var name;

And, to no one's surprise, it actually gets executed successfully without throwing any errors and simply produces the output: undefined.

Now, let's see what happens when we try to do the same with let:

document.write(name);
let name;

Try to execute this and see how JavaScript throws an error similar to this:

JavaScript error: Uncaught ReferenceError: Cannot access 'name' before initialization.

One thing I want to clear up here is that, in case you're using var for the declaration of variables in JavaScript, it is only the declaration which gets hoisted to the top and not an assignment. For example:

document.write(name);
var name = 4;

It again outputs undefined and not 4.

So, now you have enough reasons to see why the developer community recommends using let in place of var.

References

Recommended Articles

Topics:
javascript ,web dev ,javascript tutorial ,javascript tutorial for beginners

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}