Variable Declaration in JavaScript

Summary

This tutorial will cover the following concepts:
• Variables in JavaScript
• Declaration and Initiation of Variables
• The var, let, and const keywords
• Variable Scope and Hoisting

WHAT ARE VARIABLES

Variables in JavaScript are containers for storing re-usable data values. JavaScript is a loosely typed language, which means variables can hold values with any type of data. As such, a variable, once declared, could store an integer, a string or any other data type.

DECLARATION OF VARIABLES

Declaring a variable could be simply explained as creating a variable. The syntax for declaring variables is the variable keyword followed by the variable name.

Prior to ES6, variables were only declared using the var keyword. However, in ES6, a variable could be declared using either of these keywords: var, const or let.

var x;
let x;
const x;

Using any of these keywords creates a variable named x. x is known as an identifier in JavaScript. There are certain rules guiding the naming of variables. The topic will not be covered within the scope of this article, but you can find more information on that here.

In the above example, the variable x has been declared, but it has no value stored in it yet, which means x is undefined. Assigning a value to x is known as initiation of the variable. This is done using the identifier, the assignation sign (=) and the value being assigned. The syntax for this is:

Identifier = value; e.g.
x = 5;

Now the variable x has a value of 5, which means if we were to console.log(x), it would return 5. This snippet of code x + 5 would give 10 as a result.

To declare and initiate a variable at the same time, follow this syntax:

var identifier = value; e.g.
var x = 5;

To do this for multiple variables at the same time:

//declaring multiple variables in one statement
var x, y, name;
//declaring and initiating multiple variables in one statement
var x = 5, y = 7, name = “Tolu”;

The same applies for the keywords const and let, except that variables declared with const must be initiated at the same time.

DIFFERENCES BETWEEN VAR, LET AND CONST

The keyword var was the default keyword for declaring variables prior to ES6. let is very similar to var, with the major difference being its constraints in scope, a concept which will be discussed later in this article.

The const keyword is used to declare variables whose values remain unchanged throughout the script. With the let and var keywords, variables can be reassigned, that is, they can have new values assigned to them after initiation. The same however, is not true for the const keyword.

var name = “Tolu”;
name = “John”; //will not give an error
console.log(name); //John

let name = “Tolu”;
name = “John”; //will not give an error
console.log(name); //John

const name = “Tolu”;
name = “John”; //will give an error
console.log(name); //error message

Variables declared with const are not literally constant, but they possess a constant reference. This is why primitive data types such as numbers and strings will be immutable, but the properties of objects and arrays in const variables can be changed. This does not mean, however, that they can have entirely new arrays or objects assigned to them.

const studentInfo = {name: “John”, school: “UNILAG”, age: 18};
studentInfo.school = “UNILORIN”, //will not give an error
studentInfo = {name: “Ada”, school: “Bowen”, age: 20}; //will give an error

HOISTING AND SCOPE

Scope

The scope of a variable is the part of the script from where the variable can be directly accessed.

Prior to ES6, JavaScript had two major scopes:

  1. Global Scope
  2. Function Scope

ES6 introduced Block Scope.

Variables with global scope are declared outside of functions and can be accessed throughout the script. Variables with function scope are, as the name implies, declared inside functions and can only be accessed within the function in which they are declared.

var x = 5, y = 7;
function sum() {
    var total = x + y;
    return total;
}
// x and y have global scope
// total has function scope

In the above example, the variable total cannot be accessed outside the function sum. If we tried to run this code snippet console.log(total) outside the function sum, it would return an error.

Variables with block scope can only be assessed within the block in which they are declared. A block is a portion of code enclosed by curly braces (a good example of this would be a variable declared within a loop or an if...else statement).

let arr = [1, 2, 3, 4, 5];
for (i = 0; i < arr.length; i++) {
    let example = i + 2;
}
//example has block scope and cannot be accessed outside the block.

Only variables declared with the let and const keywords can have block scope.

Hoisting

In JavaScript, variables can be initiated and used before they are declared.

x = 5;
console.log(x); //5
var x;

This is attributed to hoisting. When parsing the script, the JavaScript engine moves all variable declarations to the top of their scope. The above code example is actually interpreted by the JavaScript engine as this:

var x;
x = 5;
console.log(x); //5

Note: Only variables declared with var are hoisted. Variables declared with the let and const keywords are not hoisted.

It is best practice to declare your variables at the beginning of the scope. This will help avoid unforeseen bugs.

CONCLUSION

Hopefully, you now understand how to declare, initiate and reassign variables. You also understand the differences between var, let and const, alongside their different use cases and implications. In addition, you have a basic grasp of the concepts of scope and hoisting. If you understand these concepts, you now understand the fundamentals of how variables work in JavaScript.

Further Reading:
Scope: w3schools.com/js/js_scope.asp
Hoisting: w3schools.com/js/js_hoisting.asp
let vs. var: javascripttutorial.net/es6/difference-betwe..