Var vs Let in Javascript




Many developers who used to write code on Javascript don’t care about the big differences in use between Var & Let and maybe they don’t even know.


                                          


                   What are the differences between Let and Var?

Basically, it’s one of the most asked questions in the job interviews, even among the developers them selfs.

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.

 

So let’s define the differences by defining how they behave differently in many roles:

Scoping:

  • Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
  • ES6 introduced the let keyword which defined a Block Scope in JavaScript
  • That means that the variables defined using let inside a {} Block can’t be accessed from outside the block.
  • While variables defined using the var inside a {} Block could be accessed from outside the block.





    Defining let in a Scope




    Defining var in a Scope

Hoisting:

  • Variables are defined with var are Hoisted to the top and can be initialized at any time, which means you can declare the variable before it’s defined because the var will go to the top of the file.
  • While Variables defined with let are Hoisted to the top as well but not initialized so if you use the let variable before it’s initialized it will give a Reference Error.




Global Object:

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





Redeclaration:

The variables defined with let can’t be redeclared, So you can’t redeclare the variables defined using the let keyword accidentally.

When the variables defined with variable could be redeclared.

See the example:

Redeclaring variables defined using var & let




so as you see in the example above that we created variables using let and var, then we redeclared them and logged them on the console, and the result: the variable declared using let which is Jack didn’t change while the variable declared using var which is John change after declaring and become Johnny.



At the end of the article, I would like to thank you for your attention and I hope that will help you to understand better the main differences between let & var keywords.


Don’t forget to follow me on Twitter where I tweet about Game Development and programming, in general, →Twitter

And my Github account →Github


 



Comments

Popular posts from this blog

Tic Tac Toe

Angry Birds Using Unity 2D