CONSTANTS

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.
  • JavaScript const variables must be assigned a value when they are declared.
  • Declaring a variable with const is similar to let when it comes to Block Scope.

When to use JavaScript const?

As a general rule, always declare a variable with const unless you know that the value will change.

Use const when you declare:

  • A new Array
  • A new Object
  • A new Function
  • A new RegExp

Constant Objects and Arrays

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
  • Change the elements of constant array
  • Change the properties of constant object

Constant Arrays

 // 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"); 

Constant Objects

 // 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"; 


This free site is ad-supported. Learn more