var, let, always use const?

We can declare a variable in JavaScript using any of the three keywords var, let, and const. In this article, we’ll discuss the key properties and consequences of using each of these keywords. I personally prefer to use const always wherever possible because of its secure nature, more on that below.

Scope of a variable

Before we start with the declaration of variables it is important to understand what is the scope of a variable and the types of scope in javascript.

Wait, what is the scope of a variable?

The scope of a variable in programming is the visibility or availability of a declared variable. In javascript, there are three types of scope namely,

  • block scope
  • global scope
  • function scope

And the keywords we use to declare a variable define its scope.

Global vs Block vs Function scope

Global scope
A variable in javascript is said to have global scope when it declared outside all blocks and is available throughout the window.

var foo = "hi ";
let bar = "hello ";
const baz = "hola ";
function sayHi() {
    console.log(foo, bar, baz);
 }
sayHi(); // hi hello hola

Function scope
A variable declared in a function can only be accessed inside the function.

function helloWorld() {
    var foo = "hi";
    let bar = "hello";
    const baz = "hola";
}
console.log(foo, bar, baz); 
// ReferenceError: foo,bar,baz are not defined

Block scope
In block scope, a variable’s scope is limited by a set of curly braces in javascript, the braces that form a block in any use case like if-else, switch case, etc.

if (true) {
     var foo = "hi";
     let bar = "hello";
     const baz = "hola";
}
console.log(foo); // hi
console.log(bar, baz); // ReferenceError: bar is not defined
console.log(baz); // ReferenceError: baz is not defined

Yes, as you can say by the output var is not block-scoped, more on it below.

Var

Before ES6 (ES2015) the var was the only keyword to declare a variable. Let’s have a look at the properties of var.

Scope of var

Variables declared using var are globally scoped and function/locally scoped. var is globally scoped, once declared globally it can be used anywhere.

var message = "Hello js";
function sayHi() {
    console.log(message);
}
sayHi(); // Hello js

var is also function scoped, if declared inside a function then it cannot be accessed outside the function.

function sayHi() {
    var message = "Hello js";
}
console.log(message); // ReferenceError: message is not defined

The problem with var

The major problem with var is that it can be re-declared and updated anytime, anywhere.

var message = "Hi";
var message = "Hello";
function someRandomImportFunction() {
    var message = "Hola";
    console.log(message); //Hola
}
someRandomImportFunction();
console.log(message); //Hello
if (true) {
    var message = "Stonks";
}
console.log(message); //Stonks

var can create a lot of problems as some random block of code can red-declare an existing variable and we will not even get a warning that it did. I can confidently say never, ever use var.

Let

Let is perfectly suitable in most cases, when in doubt use let. Variables declared with let are block-scoped and cannot be re-declared. A variable declared with let inside any block of code cannot be accessed outside of it.

function add() {
    let a = 12; 
}
console.log(a); // ReferenceError: a is not defined

if(true){
    let n = 14;
}
console.log(n); // ReferenceError: n is not defined

let b = 10;
let b = 11; // Identifier 'b' has already been declared

The let variables cannot be re-declared but they can be re-assigned/updated.

let name = "NEO";
name = "ANDERSON";

Const

const means constant, it is one of the most powerful ES6 features as it helps us keep our code clean and secure. Variables declared with const are block-scoped and cannot be re-assigned. Sounds similar to let but let’s have a look at the re-assigning part,

const num = 100;
num++; // Not possible
num = 110; // Not possible

This makes us think we can only use a constant for things like
const pi = 3.144444;

Important
Const needs to be initialized when it is declared else it will throw an error.

const num;  ❌
// Uncaught SyntaxError: Missing initializer in const declaration

const bill =100; ✅

But, const with objects is a powerful and widely-used combination, because a constant object cannot be updated but its properties can be updated. So, you can create a constant object with all the properties that you need and then access/modify its properties.

const person = {
    name: "Neo",
    city: "Matrix"
}
person.name = "Abhi"; 
person.city = "Matrix Reloaded";
console.log(person);
// { name: 'Abhi', city: 'Matrix Reloaded' }

Can we use const everywhere?

Yes, you’ll be surprised by the possibility of using const almost everywhere in our code, and there are two main reasons for this. First, our code is block-scoped i.e a variable exists and can be accessed only where it is supposed to be and this saves memory and also protects the code. The second reason is that in javascript we deal with objects and arrays more often which need not be re-assigned as a whole making perfect use of const.

📍 FunFact: both let and const have been introduced with ES6 (ES2015).

📝 Note: If we declare a variable in javascript without using any of the keywords simply like a=12, by default it will have global scope. This type of declaration might cause trouble later and is not recommended.

What do you use more often, let or const?

Reference