Variables in JavaScript

If your variable won’t be updated during the run of the scripts or you don’t want the variable to be overwritten, you should always use const.

One of the problems in JavaScript is that variables, when they are not defined using the var keyword, they become global. Declaring variables without var can end up breaking your code because your variable can override a previously declared one with the same name.

var message = "This is the global Scope!";
function changeMessage(){  
  message = "This is this inside the function"
}
changeMessage();
console.log(message); //This is inside the function

As you can see, the message variable was changed from inside the function. The issue may be solved by adding var before the message inside the function. To put this in a more real-world example from the past, let’s say that you wanted to use jQuery and PrototypeJS together in your project. They both used the “$” dollar sign as part of the libraries. If you declare jQuery first, then PrototypeJS will override jQuery’s dollar sign; thus,  breaking your code and plugins that depend on jQuery.

<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7/prototype.js"></script>
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script>console.dir($);</script>

The previous code will return the jQuery object. Nevertheless, if we swipe the position of the scripts, it would return the function from PrototypeJS used to get elements by ID. jQuery has a way to avoid conflicts over the user of the dollar sign but it is out of the scope of this post.

It has always been recommended to use “var” for all variables of your code because it makes your code more readable and you avoid unpredictable behavior in your scripts. But, even declaring a variable has its problems. When var is used, it declares the variable at the function scope instead of the block scope. Let see an example to illustrate this behavior.

var arr = [23,34,5,7,8,47,221,99,2,761,14,8];

for(var i = 0; i < arr.length; i++){
    //processing the items of the array
}
console.log(i); //12

The variable i is out of the block scope instead of staying inside the “for loop”. That is why it was recommended to declare all the variables at the top even if they are used in loops because it illustrates and explains the real behavior of the code (Hoisting) and avoids the confusion of the scope of the variable. Example:

var arr = [23,34,5,7,8,47,221,99,2,761,14,8],
    len = arr.length,
    i = 0;
for(i; i < len; i++){
    //processing the items of the array
}
console.log(i); //12

The variables in JavaScript are hoisted. This means that the variables will move to the top of the function at run time. However, the assignment to the to those variables will stay in the place where they appear. Example:

console.log(i); //"ReferenceError: i is not defined

In the previous example, it returns an error because the variable is not defined. However, if you define the variable right after the statement, it will return undefined which means that the variable is acknowledged before console.log(i) runs.

console.log(i); //undefined
var i;

Even when the variable is acknowledged by the browser, it does not mean that you will get the assigned variable because the value is assigned at the line specified. Thus, the following example will still return undefined.

console.log(i); //undefined
var i = 100;

let To the Rescue!

The let keyword was first introduced in JavaScript 1.7 and implemented by Firefox 2 in October 2006 (A long time ago!).  But, it is is not supported by IE 10 and older. If you want to know what browsers support it, please review the great ECMASCRIPT 6 support table by Kangax.

With the new let keyword, we can declare variables that only belong inside the block where it is declared. They are not going to be part of the scope of the function unless it is defined outside of a block of code. Let’s rewrite example to use the let keyword instead of var:

var arr = [23,34,5,7,8,47,221,99,2,761,14,8];
for(let i = 0; i < arr.length; i++){
    //processing the items of the array
}
console.log(i); //ReferenceError: i is not defined

The variable “i” does not escape out of the “for” loop. Moreover, if we try to access “i”, it will throw an error because the variable is not defined outside of the loop. For several years it has been recommended to use the let over var or global variables because you let won’t leak out of the block scope and it will help you to create a more predictable code that is easier to debug.

Should I use Const?

If your variable won’t be updated during the run of the scripts or you don’t want the variable to be overwritten, you should always use const. Before the const keyword, developers were forced to use var even if the variables were not expected to change. However, with const, you can catch some bugs in your code since it will return an error if you try to assign a value to an already declared constant.

const hello = "Hello";
hello = "New value"; //"TypeError: Assignment to constant variable.

Conclusion

Always try to use let or const in your scripts. All modern web browsers support it and it makes your code more predictable and easier to understand since they won’t overwrite previously declared variable somewhere else in your code.