Var vs Let in JavaScript

In this article, we would be discussing the long run debate of var vs let in Javascript. We would also be discussing why the usage of let is increasing in dev communities.

Var vs Let in JavaScript | Full Stack Geek
Var vs Let in JavaScript | Full Stack Geek


Declaring variables in Javascript was not a cake walk up 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), it would lead to a mess as your code base grows significantly and hence let was introduced which would 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 great depth.

Why Let is Superior to Var:

Now, we would be discussing in great depth, why on earth 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:

So, consider that you are using the old method of declaring variables in Javascript, i.e, you are using var for the same instead of let. Hence you are allowed to do this:

var name = 'abc';  
name = 'def';  
var name = 'ghe';  

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

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

let name = 'abc';  
name = 'def';  
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, we do not create new scope while using var and hence, it would create 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 for loop completes.
If you have used var to declare the variable inside the for loop, it would not reset that variable even after execution of the for loop as, except for functions, nothing would create a new scope for variables declared with var, while on the other hand, let is block-scoped, it would create a new scope for the local variable as soon as a new for loop (or any other construct like if statement, while loop, 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 live 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 for yourself:

var name;

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

Now, Let us see what happens when we try to do the same with let:

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 here, that in case of using var for declaration of variables in Javascript, it is only the declaration which gets hoisted to the top and not an assignment, For Example:

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.

Recommended Articles:

If your learning appetite is still left, you are suggested to read below articles:

Source link


المشاركات الشائعة من هذه المدونة

لماذا يحتاج الذكاء الاصطناعي دائمًا إلى الرقابة البشرية ، لا يهم مدى ذكائه

102 Christmas Greeting Cards Collection 6 Unique Animal Designs with Envelopes for Winter Merry Christmas Season, Holiday Giving, Xmas Cute Gifts Cards