Saturday, 9 February 2019

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






Introduction:

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.

Suggested Read: Redis vs MySQL Benchmarks


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';  
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 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';  
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, 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:

document.write(name);
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:

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 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:

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:

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


Liked this blog? Don't miss out on any future blog posts by Subscribing Here

No comments:

Post a Comment

Labels

JavaScript (9) PHP (7) MySQL (4) Arrays (3) Laravel (3) variables (3) Elasticsearch (2) functions (2) Beats (1) Benchmark (1) CakePHP (1) Callbacks (1) Cluster (1) CodeIgniter (1) Cookies (1) DBMS (1) Documents (1) ELK stack (1) Frameworks (1) Indices (1) InnoDB (1) Kibana (1) Learning (1) Logstash (1) MyISAM (1) Nodes (1) OTP (1) Redis (1) Replication (1) Roadmap (1) SQL (1) Searching (1) Sessions (1) Sharding (1) Storage Engines (1) Symfony (1) Twilio (1) Ubuntu (1) books (1) expired time (1) let (1) remember me (1) var (1)