One of the fundamental topics I’d like to briefly address, given that it appears in JavaScript examples, are the variable declarations provided by JavaScript.
As a habit inherited from the past, I frequently use var, but with the introduction of new features in ES6 (or ES2015), we now have alternative options: let and const.
Of course, different use cases may arise depending on the specific needs. Before diving into the details, a brief reminder is in order. Both let and const are supported in modern browsers. Therefore, it’s beneficial to evaluate their usage based on the requirements of your project. For more detailed information about browsers that support these features, you can refer to the ECMAScript Compat Table1. After this brief reminder, we can proceed to examine the features of these declarations.
JavaScript: Variable Declaration
The act of creating a variable without assigning a value is known as variable declaration. Assigning an initial value to a variable is referred to as variable initialization. In the following example, the variables x, y, and z are declared in different ways and are assigned their initial values. When you run the code, you’ll encounter one warning and seven errors. We’ll discuss these in detail under the section Variable Declarations2.
x
x = 2;
var x = 4;
let y
y = 2;
let y = 2;
var y = 4;
const y = 6;
const z
z = 2;
let z = 4;
var z = 8;
JavaScript: Variable Declarations
ECMAScript syntax resembles that of Java and is designed as a simple command-line scripting language. For instance, specifying the type of a variable3 is usually unnecessary. A variable defined outside of a function or block is globally accessible, reassignable, and capable of acquiring a new value. However, as code grows in complexity, accessing the value of a variable defined within a scope, creating a new variable, or assigning a new value to an existing variable may lead to various issues. This is because variables are typically considered in relation to the areas in which they are used, and are evaluated within a specific scope context.
A globally declared variable can be accessed from any location. A variable declared within a function, i.e., locally, is only accessible within the function and its nested functions. At this point, var comes into play. You can test the following examples jsfiddle.
Var
var is the most basic variable declaration statement in JavaScript. If no value is assigned to a variable declared with var, the variable is initialized as undefined.
var x;
var y = 5;
console.log(x*y);
x = 10;
function fnc(){
var y = 2;
console.log(x*y);
}
fnc();
console.log(x*y);
A variable declared with var is accessible from any location where it is defined (global scope). However, if it acquires a new value within a scope, that value is processed within the relevant scope (function scope) and any nested functions. In the example above, y takes the value 2 within the function and operations are performed based on this value. Outside the function, however, operations are performed using the value 5.
Now, try running the following code.
x = 10;
function fnc(){
var y = 2; // new value
z = 2;
console.log(x*y);
}
fnc();
console.log(x*y);
console.log(x*z);
In the examples above, we observed how the variables x, y, and z behave; we changed their values and redeclared the variables. What if we don’t want a variable’s value to be changed later, or if we only want a variable to be declared once and then able to assign new values afterward? In such cases, the const and let declarations provide a solution4.
Const
The const declaration allows us to create variables with fixed values. The value assigned when the variable is declared cannot be changed later, and the variable can be declared only once. However, there may be certain exceptions. For example, a const variable declared globally can be accessed within a function scope5.
const x = 0;
function fnc(){
x = 20;
y = 2;
console.log(x*y);
}
fnc();
console.log(x*y);
You are likely to encounter an error inside the fnc function when trying to modify x. However, if you add var before the variable, you will notice that the error disappears. On the other hand, if you try to redeclare or assign a new value to x outside the function scope using var, you will encounter an error again. Finally, if we declare the variable y as const inside the function, all restrictions apply within that function. Outside the function scope, the variable y can be redeclared and assigned a new value. However, its value cannot be accessed within the function.
Let
With let, we can assign new values to a variable. However, we cannot redeclare it. The let declaration has block scope. That is, a variable declared with let can only be used within the curly braces {} that contain its declaration (for example, within if, for, etc.), and it cannot be accessed outside of that scope6 7.
let x = 10;
function fnc(){
let y = 2;
console.log(x*y);
}
fnc();
console.log(x*y);
let y = 4;
console.log(x*y);
y = 8;
console.log(x*y);
var y = 16;
console.log(x*y);
When you run the code, the first error you’ll encounter will be related to the fact that the variable y was previously declared with let. The other error will be related to the fact that the variable y was already declared. However, both errors pertain to different y declarations. By successively removing the y variables in the above example, you can observe how the result of x*y changes. Let’s summarize all these details in a table.
| Features | Var | Const | Let |
|---|---|---|---|
| Global Scope | + | + | + |
| Function Scope | + | + | + |
| Block Scope | - | + | + |
| Can be redeclared? | + | - | - |
| Can it take a new value? | + | - | + |
Finally
It’s beneficial to look beyond just one point in JavaScript variable declaration. You might have seen in some JavaScript code that a value is assigned to a variable before it is declared. This phenomenon is known as hoisting. During JavaScript compilation, the relevant operations are executed in a specific order, which is why we don’t encounter errors.
x = 10;
console.log(x);
var x;
y = 10;
console.log(y);
const y;
z = 10;
console.log(z);
let z;
However, this behavior applies only to var. When declaring with let or const, an error will occur. Using const will return an error indicating that the variable x is permanently declared (i.e., declared with const), while using let will return an error indicating that the variable x was previously declared.
Further Reading
- Tyler McGinnis, var vs let vs const in JavaScript (Jan 1, 2019), tylermcginnis.com
- Sarah Cahima, Var, let and const- what’s the difference? (Oct 25, 2017), dev.to.
- Aurelio De Rosa, ES6 in Action: let and const (Apr 6, 2018), sitepoint.com