Explained - The Difference Between Var, Let and Const in JavaScript

Explained - The Difference Between Var, Let and Const in JavaScript

let var const.jpeg

Var - Let - Const

A lot of shiny new features came with the introduction of ES2015 (ES6). One of the features is the addition of let and const which is also used for variable declaration. How are they different from our good old friend var.

Let's Get Started

In this article, we'll discuss var, let and const with respect to their scope, how they are declared and defined(updated).

A little cheat sheet to get you started

var-let-const-cheatsheet.png

Var

The good old way of declaring a variable is by using the var keyword. They were few issues associated with declaring a variable with var that was why it was necessary for a new way to declare variables be introduced.

Var is function scoped

Scope in this case is essentially where the variable is available for use. When a variable is declared using the var keyword inside a function, that variable is function scoped and can only be accessed within that function.

function country() {
     var countryName = 'Nigeria';
     console.log(countryName)
}
country() // Output is Nigeria

When you try to access the variable countryName outside it's function scope, it will output an error.

function country() {
     var countryName = 'Nigeria';
}
console.log(countryName) 
// Uncaught ReferenceError: studentName is not defined

When you declare a variable outside a function, that variable becomes globally scoped

var studentName = 'John' 
function name(){
     console.log(studentName)
}
name() // Output is John

Redeclaring and Redefining(updating)

A variable declared with var can be redeclared and updated.

// Redeclaring a variable
var name = "John Doe";
var name = "Jane Sam";
console.log(name) // Jane Sam

When redefining or updating the value of a variable, you don't use the var keyword

// Redefining/Updating a variable
var name = "John Doe";
name = "Jane Sam";
console.log(name) // Jane Sam

Let

Let was introduced together with the new features in ES6 and is now preferred for variable declaration as it comes with new improvement to var declarations.

Let is block scoped

A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within a curly braces is a block of code.

let greeting = "say Hi";
   let times = 4;

   if (times > 3) {
        let hello = "say Hello instead";
        console.log(hello); // "say Hello instead"
    }
   console.log(hello) // hello is not defined

Let can be updated but not re-declared.

Just like var, a variable declared with let can be updated within its scope. Unlike var, a let variable cannot be re-declared within its scope. So while this will work:

//Redeclaring a let variable
let name = "John Doe";
let name = "Sam Doe";
console.log(name) 
// Uncaught SyntaxError: Identifier 'name' has already been declared

But a variable declared with let can be updated or redefined

//Redefining(Updating) a let variable
let name = "John Doe";
name = "Sam Doe";
console.log(name) // Output is Sam Doe

Const

Variables declared with the const maintain constant values i.e. their values cannot change. Const declarations share some similarities with let declarations.

Const are blocked scoped

Similarly to let, const are also blocked scoped, meaning they can only be accessible within a block of code. Trying to access a const variable outside it's block will return error.

let name = "John"
if(name == 'John') {
    const number = 2
}
console.log(number) // Uncaught ReferenceError: number is not defined

Const cannot be updated or re-declared

This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared.

// Cannot be redeclared
const name = "Jane Doe";
const name = "Sam Doe";
console.log(name) 
// Uncaught SyntaxError: Identifier 'name' has already been declared

You can't redefine a const variable

// Cannot be redefined
const name = "Jane Doe";
name = "Sam Doe";
console.log(name) 
// Uncaught TypeError: Assignment to constant variable.

Conclusion

Why would you chose “let” over “var”?

While programming in JavaScript it is a good practice not to define variables as global variables. This is because it is possible to inadvertently modify the global variable from anywhere within the JavaScript code. To prevent this one needs to ensure that the scope of the variables are limited to the code block within which they need to be executed.

In the past before keyword let was introduced as part of ES6, to circumvent the issue of variable scoping using var, programmers used the IIFE pattern to prevent the pollution of the global name space. However since the introduction of let, the IIFE pattern is no longer required, and the scope of the variable defined using let is limited to the code block within which it is defined. - Prashant Ram

Any Questions?

If you have any questions regarding this topic or any questions generally about programming, you can leave me a message on Twitter and I will do well to respond as soon as possible. Thanks.

Gracia's #Stay Safe