bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/JavaScript Foundations
JavaScript•JavaScript Foundations

JavaScript Const

Concept visual

JavaScript Const

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

The const keyword was introduced in

ES6 (2015)

Variables defined with const cannot be

Redeclared

Variables defined with const cannot be

Reassigned

Variables defined with const have

Block Scope

Cannot be Reassigned

A variable defined with the const keyword cannot be reassigned:

Example

const PI = 3.141592653589793;
PI = 3.14;      // This will give an error
PI = PI + 10;   // This will also give an error

Must be Assigned const variables must be assigned a value when they are declared:

Correct const PI = 3.14159265359;
Incorrect const PI;
PI = 3.14159265359;

When to use JavaScript const?

Always declare a variable with const when you know that the value should not be changed.

Use const when you declare:

A new Array

A new Object

A new Function

A new RegExp

Constant Objects and Arrays

The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value. Because of this you can NOT:

Reassign a constant value

Reassign a constant array

Reassign a constant object

But you CAN:

Change the elements of constant array

Change the properties of constant object

Constant Arrays

You can change the elements of a constant array:

Example

// You can create a constant array:

const cars = ["Saab", "Volvo", "BMW"];

// You can change an element:

cars[0] = "Toyota";

// You can add an element:

cars.push("Audi");

But you can NOT reassign the array:

Previous

JavaScript toString()

Next

JavaScript Logical Operators