JavaScript const

In this section we’re assuming you’re already familiar with variables in general and also know how to create a variable via the let keyword.

So far, we learned how to create an identifier via the var and the let keywords. The third way of creating an identifier is via the const keyword.

The const stands for constant and that is used when we want to create an identifier that its value won’t change throughout the program’s execution.

For example the value of the PI in mathematic is 3.14…. This is one of those types of values that we know that it won’t change no matter how we design a program. Obviously because the value is constant and won’t change at all, it’s a perfect candidate for a const identifier. After all, a const identifier initializes only once and that’s it. We can’t reassign anther value to a const identifier.

Example:

const Pi = 3.14;

Notes:

  • An identifier that is declared as `const` cannot change its value
    after being initialized. Changing the value after initialization, will
    return error.

  • Also a `const` identifier need to be initialized right where we
    declare it. We can’t initialize a `const` identifier in a separate
    statement.

Example;
const Pi;
Pi = 3.14; //ERROR…
  • Also just like the `let` keyword, identifiers that are created
    via the `const` keyword are block scope. More about
    this in the scope section.