JavaScript

JavaScript Variables – What is the difference between var, let, and const in javascript?

In ECMAScript 2016, JavaScript introduced two new methods to declare variables with let and const keywords. JavaScript only had one option to declare variables before 2016 i.e. the var keyword. In this article we will learn why there are three different ways to declare variables in JavaScript; we will also cover the difference between these three articles. Additionally, this article will also introduce you to concepts such as variable scope and hoisting. So let’s get started by understanding what is variable scope:

What is Scope in JavaScript

In JavaScript, the scope is defined by curly brackets. It defines a block of code that needs to be executed together. JavaScript has two kinds of scopes:

  • Function-scope
  • Block-scope

Function-scope : Any variable In JavaScript created inside a function using var is function-scoped. Its visibility is restricted to the definition of the function and it cannot be accessed from anywhere outside the function:

function showMessage() {
  var message = 'Hi from Linuxhint';
 
  console.log("in: " + message); // 'Hi, Linuxhint!'
}

showMessage();

console.log("out: " + message); ReferenceError: message is not defined

Block-scope : A block of code in JavaScript is defined by curly braces. This type of scope will help us prominently differentiate between the three methods of declaring variables:

Following is an example where we have declared variables with var, let, and const in an if block and then logged them to the console:

if (true) {
  var message1 = 'Hi from Linuxhint';
  let message2 = 'Hello from Linuxhint';
  const message3 = 'Hi again from Linuxhint';

  console.log("in: " + message1); // 'Hi from Linuxhint';
  console.log("in: " + message2); // 'Hello from Linuxhint';
  console.log("in: " + message3); // 'Hi again from Linuxhint';
}

All of the variables have been logged to the console without any error as they were logged from the same block.

However, if we try to log them from outside of the if block, the below-mentioned error will appear:

if (true) {
  var message1 = 'Hi from Linuxhint';
  let message2 = 'Hello from Linuxhint';
  const message3 = 'Hi again from Linuxhint';

  console.log("in: " + message1); // 'Hi from Linuxhint';
  console.log("in: " + message2); // 'Hello from Linuxhint';
  console.log("in: " + message3); // 'Hi again from Linuxhint';
}

console.log("out: " + message1); // 'Hi from Linuxhint';
console.log("out: " + message2); // ReferenceError: message2 is not defined
console.log("out: " + message3); // ReferenceError: message3 is not defined

How to use var to declare a variable in JavaScript

Before ECMAScript 2016 var was the only method of declaring a variable in JavaScript but it had several issues associated with it, so new methods were introduced which could be used to declare variables. We will first understand var and then we’ll talk about these issues:

Scope of var : Variable scope basically means where the variable will be available to use. Variables that are declared with the var keyword either have global or local scope.

Variables that are declared outside function block using var have global scope. Global scope means that a variable is available to use anywhere in the window.

When the variable is declared inside a function it is function-scoped which means that it can only be used inside the function:

To understand further, look at the example below:

function showMessage() {
  var message = 'Hi from Linuxhint';
}

Here, the message is function scoped so it cannot be accessed outside of the function. So if we do this:

function showMessage() {
  var message = 'Hi from Linuxhint';
}

console.log("out: " + message); // ReferenceError: message is not defined

This will give us an error which is because the message is not available outside the function.

var outside of a for-loop : The variable “i” can be accessed from the outside of the for-loop.

for (var i = 0; i < 5; i++) {
  console.log("in: " + i);
}

console.log("out: " + i);

var variables can be re-declared and updated : In JavaScript variables declared with var keyword can be redeclared and updated in the same scope:

function showMessage() {
  var message = 'Hi from Linuxhint';
  message = 'Hello from Linuxhint';
  var message = 'Hi again from Linuxhint';

  console.log(message); // 'Hi again from Linuxhint';
}

showMessage()

How to use let to declare a variable in JavaScript : The let keyword is now preferred over var for variable declarations; it comes with a few improvements over var.

let is block scoped : In JavaScript, a block of code is the collection of statements that are bounded by a pair of curly brackets {}. A variable declared using the let keyword is only available to use within that block and cannot be accessed from outside:

if (true) {
  let message = 'Hi from Linuxhint';

  console.log("in: " + message); // "Hi from Linuxhint"
}

console.log("out: " + message); // ReferenceError

If we use the message outside of the block where it was defined, it will return an error. This is because let variables are block-scoped.

let outside of a for-loop : The following example demonstrating the let variable output using for loop:

for (let i = 0; i < 5; i++) {
  console.log("in: " + i);
}

console.log("out: " + i);

let can be updated but not re-declared : A variable declared with let can be updated within its scope just like var, but unlike var, it cannot be redeclared:

let message = 'Hi from Linuxhint';
message = 'Hello from Linuxhint';

The console is completely empty and is not returning any errors. These statements will return an error:

let message = 'Hi from Linuxhint';
let message = 'Hello from Linuxhint'; // SyntaxError: Identifier 'message' has already been declared

However, redefining the same variable in a different scope using let does not return any error:

let message = 'Hi from Linuxhint';
if (true) {
  let message = 'Hello from Linuxhint';
  console.log("in: " + message); // "Hello from Linuxhint"
}
console.log("out: " + message); // "Hi from Linuxhint"

The let keyword treats these two variables as different if they are in different scopes so it does not return any error; this feature of the let keyword makes it a better choice than var. When using let, you can reuse variable names in different scopes without worrying about whether you have used that variable name before.

How to use const to declare the variable in JavaScript

The variables declared using the const keyword have constant values. This means that their values cannot be changed/reassigned. Similar to the variables declared with the let keyword, the variables declared with the var keyword are also block-scoped.

const can’t be re-declared or reassigned : The variables declared with the keyword const cannot be redeclared or reassigned within the same scope. So if we have declared a variable with const keyword, we cannot do this:

const message = 'Hi from Linuxhint';
message = 'Hello from Linuxhint'; // TypeError

Nor will we be able to do this:

const message = 'Hi from Linuxhint';
const message = 'Hello from Linuxhint'; // SyntaxError

Every variable which is declared using the const keyword must be initialized at the time of its declaration.

This behavior of the const keyword somehow changes when it comes to objects. While the object declared cannot be updated, its properties can be changed

So, if we declare an object with const:

const user = {
  name: "Steve",
  age: 13
}

While this cannot be done:

user = {
  userName: "Harry",
  grade: "3rd"
} // TypeError: Assignment to constant variable.

This can be done:

user.name = "Harry";

This will change the value of the user.name without returning any errors.

Final review

 

Variable Declaration Function-scope Block-scope Redefinable
var
let
const

Conclusion

It is generally a good practice to avoid using var to declare variables in JavaScript because the function scope is confusing and is not as obvious as the block scope. The let and const keywords encourage devs to use better coding practices. You should generally use let for the variables that you’ll need to reassign and use the const keyword for all other variables. This article thoroughly explains all three variable types with examples.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.