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

JavaScript 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:

Example

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

cars = [
"Toyota""Volvo""Audi"];    // ERROR


Constant Objects

You can change the properties of a constant object:

Example

// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};

// You can change a property:
car.color = "red";

// You can add a property:
car.owner = "Johnson";

But you can NOT reassign the object:

Example

const car = {type:"Fiat", model:"500", color:"white"};

car = {type:
"Volvo", model:"EX60", color:"red"};    // ERROR


Difference Between var, let and const

 
 

Scope

Redeclare

Reassign

Hoisted

Binds this

var

No

Yes

Yes

Yes

Yes

let

Yes

No

Yes

No

No

const

Yes

No

No

No

No

What is Good?

let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.

What is Not Good?

var does not have to be declared.

var is hoisted.

var binds to this.

Login
ADS CODE