When to use const, let, and var

When to use const, let, and var

*Plug: Feel free to check out some of my other quick programming tips here!*

If you have written any amount of JavaScript you have come across at least one of the following; const, let, var and considering you are here you thankfully decided to look up what the heck the difference is between them.

While they are technically interchangeable in many cases there is a general convention and consensus as to when and how to use these terms in your code to make it less prone to bugs and more readable.

CONST

const is short for “constant” and creates a block-scoped variable. In JavaScript a constant variable is a reference to something (value, object, etc) and that reference is immutable.

// We will define a constant ‘x’ equal to the integer 10
const x = 10;

// If we try and reassign this constant it will result in an error
x = 100; // Error

*Note that the reference being immutable doesn’t mean the object it references is immutable.

// We will define a constant ‘x’ equal to an object
// The object will have property ‘foo’ with a value of 10
const x = {foo: 10};

// Because the object is mutable when we try and reassign 
// the ‘foo’ property of this object it will succeed
x.foo = 100; // Success

Generally speaking when you assign something as a const you are indicating to the reader that you dont want the value to change so you should avoid mutating references when possible or you can make troubleshooting more tedious.

LET

let is similar to const as they both are used to declare block scoped variables but as the name implies it “lets” the variable equal a value and that variable can be reassigned in the future.

// We will define a variable ‘x’ equal to the integer 10
const y = 10;

// If we try and reassign ‘x’ it will succeed
x = 100; // Success; x is now equal to 100

You want to use let whenever you want to declare something within the scope of a function that may require reassignment. For example a for loops:

for (let i = 0; i < 10; i = i++) {
    console.log(i);
}

In this case we want to declare a variable i which only exists within the loop and will be reassigned some arbitrary number of times. Using let we indicate to the reader that this value will be reassigned, otherwise we would have used const.

VAR

‘var’ short for ‘variable’ can be used to declare a variable and optionally assign it a value. This sounds identical to let but the key difference is regardless of which line you declare var in your code the JavaScript compiler will initialize that variable as undefined at the top of that block scope, this is called hoisting. For example:

// This function will result in a “ReferenceError”
function fooLet() {
    console.log(x);
    let x = 1;
}


// This function will log ‘undefined’
function fooVar() {
    console.log(y);
    var y = 1; 
}

Less errors are good right! Why dont we use var all the time? Well the issue with hoisting is it’s implicit, if you want to initialize your variable as undefined then you can always do it manually. For example:

function implicitFoo() {
    console.log(`this will print undefined: ${x}`);
    var x = 1;
    console.log(`this will print “1”: ${x}`);
}

function explicitFoo() {
    let y;
    console.log(`this will print undefined: ${y}`);
    y = 1;
    console.log(`this will print “1”: ${y}`);

}

Isn’t explicitFoo so much more readable? Generally you want to avoid using var as side-effects and implicit logic increase the complexity of your code unnecessarily and put that burden on the person maintaining your code.

That being said there are specific cases where var does make sense, for example if you want to stop anyone from accessing a globally scoped variable in function scope:

var x = ‘some_global_value’;

function foo() {
    var x = ‘some_local_value’;
}

In this example even if another person come and adds logic to the top of foo the value will be undefined rather then falling back to the outer scope.

Conclusion

This ended up being a little less ‘quick’ than I had planned but hope the examples were clear and this will help you make your code a little more readable! Feel free to check out any of my other articles here !