Essential JavaScript

Variables with Const

Both let and const keywords were added to JavaScript to fix problems with var.

The const keyword is identical to let with one exception:

  • let will let a variable change
  • const will keep a variable constant

Think of it this way: if let creates an open box that you can take things out of and drop other things in, then const creates a box with something glued inside it.

Once you const something, you can't reassign it. If you try to reassign it, you'll get an error.

const x = 5;
x = 7; // Uncaught TypeError: Assignment to constant variable.

Is a constant still a variable?

You may wonder how the keyword const still creates variables. Aren't variables supposed to vary? Isn't that the point?

In reality, const variables can vary. Check out this example:

function sum(num1, num2) {
  const result = num1 + num2;
  console.log(result);
  return result;
}
sum(2, 3);
sum(10, 5);

The variable result can't change once it is declared. However, each time this function runs the result variable will still have a different value.

When to use const

Unless we plan on changing a variable, we should define it with const to help prevent programming mistakes.

If we try to re-declare or re-define a const variable, JavaScript will throw an error so we know that something went wrong. This is good because it gives us a chance to fix our code.


Learning Goals

Code Editor