JavaScript: Const Keyword

Profile picture for user arilio666

Const keyword is the same as Let. Well, somewhat similar to that, but it has differences. So, const maintains constant values, which means the values cannot be changed or redeclared.

Example

const pill1 = "Red Pill";
const pill2 = "Blue Pill";

console.log("Do you want the " +pill1+ " or the " +pill2+ "?");

Output:

Do you want the Red Pill or the Blue Pill?

Const cannot be redeclared nor updated

But the functionality remains the same.

const ball = 'blue';
ball = 'orange'  // error: Assignment to constant variable.

and we also cannot do this:

const ball = 'round';
const ball = 'oval';   // error: Identifier 'greeting' has already been declared

Note: Same as let const declarations are block-scoped too, so there is no need of explaining that because it's the same. Every const keyword must be initialized at the beginning of the declaration.

Const Behaviour With Objects

So the behaviour of const is somewhat different when it comes to property modification. Note that the objects cannot be updated or redeclared here, but the user can manipulate the properties.

const characters = {
    hero : 'Neo',
    heroine : 'Trinity',
    Villain: 'Smith Agents'
}

console.log(characters.hero)

Output:

Neo

Here we are doing the object-based operation. I'm giving each object declared inside the const characters a unique property that the user can access by calling them with the variable name. Now we might wonder whether we can change the property value of the object. Yes, you can.

const characters = {
    hero : 'Neo',
    heroine: 'Trinity',
    Villain: 'Smith Agents'
}

console.log(characters.hero)

characters.Villain = 'Merovingian';
console.log(characters.Villain)

Output:

Neo
Merovingian

Observe value of Villain is set to new value.

Final Verdict:

  • the var keyword is globally scoped, or function scoped, while Let and const are both block scoped.
  • Var keywords can be both updated and redeclared.
  • While on the other hand, the let keyword can be updated/changed while Let cannot redeclare it like var.
  • Const cannot do either of them.