Variables in modern JS

Variables in modern JS

Modern JavaScript Series

Three ways to define a variable

In JavaScript there are three ways to define a variable. There's the old var and the new let and const.

Var can be reassigned multiple times:

var height = 180;
height = 200; // 200

Var doesn’t throw an error if you reuse a variable name in the same scope:

var number = 150;
var number = "hello, world"; // "hello, world"

Var variables are function scoped. That means they’re available everywhere in the scope where they were created (in a function or on the global window object). It can also cause problems if you create a temporary variable for use inside an if statement for example. Since it wasn’t created in a function, it’ll become a global scoped variable:

var age = 42;
if (age > 18) {
    var retirementYears = 68 - age;  // retirementYears is a global variable!
  console.log(`You can retire in ${retirementYears} years!`)

console.log(retirementYears) // 26

let and const

Which leads us to the two modern ways of using variables. Let and const are both block scoped. That means in the above example, dogYears would be a local variable only accessible from within that if-block:

let age = 42;
if (age > 18) {
    let retirementYears = 68 - age; // retirementYears is now local to this block
  console.log(`You can retire in ${retirementYears} years!`)

console.log(retirementYears) // ReferenceError: retirementYears is not defined

Let and const will only let you declare a variable once:

let name = "John Smith";
let name = "Jane Doe"; // SyntaxError: Identifier 'name' has already been declared

Differences between let and const

Let can be reassigned multiple times, where as const can only be assigned once:

let name = "Hiro Protagonist";
name = "Henry Case"; // "Henry Case"

const age = 24;
age = 25; // TypeError: Assignment to constant variable

Note however, that the value that the const variable points to can indeed change (if it’s a mutable type). So if const points to an array, the array itself can be changed without problem:

const ages = [10, 20, 25, 32];
ages.push(40); // [10, 20, 25, 32, 40]

But you still can’t assign another value to the const variable:

const ages = [60, 85] // TypeError: Assignment to constant variable


So in conclusion, you’ll want to use let and const instead of var. You might still see var in old code or in tutorials so it’s good to know. But let and const are the only variable types that should be used in modern JavaScript.

You should use let if the variable could be reassigned later, and const if the value isn’t going to change. Some people argue that if in doubt just use const all the time and you’ll get an error if you need to use let instead. But with time it should be easier to figure out which type to use.