JavaScript Const
JavaScript Basics

JavaScript Const

  • The const keyword, introduced in ES6 (2015), is used to declare variables that cannot be redeclared or reassigned after their initial assignment.
  • Variables defined with const are confined to the block in which they are declared, similar to those declared with let, reinforcing the principle of block scoping.
  • This ensures that once a variable is set with const, its value remains constant throughout its lifecycle within that scope, promoting safer and more predictable code behavior where variables do not change unexpectedly.

Cannot be Reassigned

A variable defined with the const keyword cannot be reassigned:

Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript const</h2>

<p id="demo"></p>

<script>
try {
  const PI = 3.141592653589793;
  PI = 3.14;
}
catch (err) {
  document.getElementById("demo").innerHTML = err;
}
</script>

</body>
</html>

Must be Assigned

In JavaScript, variables declared with the const keyword must be assigned a value at the time of declaration to ensure they are immediately initialized. This is crucial because const variables cannot be reassigned later.

Correct Usage:

const PI = 3.14159265359; // Correct: `PI` is initialized at declaration

Incorrect Usage:

const PI; // Incorrect: declaration without initialization
PI = 3.14159265359; // Error: `PI` cannot be assigned after declaration

When to use const?

  • You should always declare a variable with const if you expect its value not to change throughout your program. This helps maintain data integrity by ensuring that the variable cannot be reassigned to a different value or reference.
  • Ideal use cases for const:
    • Declaring a new array
    • Creating a new object
    • Defining a new function
    • Initializing a new regular expression
    • Setting constant objects and arrays
  • Understanding const: The term const might imply that the value is constant, but it actually ensures that the reference to the value is constant. This distinction is important because it prevents the reassignment of the reference but not modifications to the object or array itself.

Limitations and capabilities of const:

  • You cannot:
    • Reassign a constant value
    • Reassign a reference to a constant array or object
  • You can:
    • Modify the elements of a constant array
    • Alter the properties of a constant object

By using const, you can ensure that identifiers are not reassigned, which helps prevent bugs and maintain the structure of your code, especially in larger, more complex applications.

Constant Arrays

When you declare an array with the const keyword, you are creating a constant reference to the array, not making its elements immutable. This means that while you cannot reassign the array to a new array or a different value, you can modify the existing elements or add new elements to the array.

Example of modifying a constant array:

const colors = ['red', 'green', 'blue'];
colors.push('yellow'); // This is allowed: adding a new element
colors[0] = 'purple';  // This is also allowed: modifying an existing element

In this example, colors remains a constant reference to the same array, but the contents of that array are freely modifiable. This flexibility allows const to be used effectively in scenarios where the structure (i.e., the array or object itself) should remain the same, but the content may change.

While you can modify the contents of an array declared with the const keyword, you cannot reassign it to a new array or a different value.

Example of what you cannot do with a constant array:

const colors = ['red', 'green', 'blue'];
// Attempting to reassign the array will throw an error:
colors = ['purple', 'orange']; // Error: Assignment to constant variable.

When you declare an object with the const keyword, like an array, you establish a constant reference to the object. However, the properties of the object can still be modified or expanded.

Example demonstrating modifications to a constant object:

// Declaration of a const object:
const car = {type: "Fiat", model: "500", color: "white"};

// Modifying an existing property:
car.color = "red";  // This is allowed: changing the property value

// Adding a new property:
car.owner = "Johnson";  // This is also allowed: adding a new property

In this example, car is a constant reference to the object {type: "Fiat", model: "500", color: "white"}. Even though the variable car cannot be reassigned to a different object or value, you can modify its properties (color) or add new properties (owner). This feature of JavaScript const provides flexibility in managing the content of objects while ensuring the stability of the reference.

While you can modify or add properties to an object declared with the const keyword, you cannot reassign it to a new object. This is because the reference to the object itself is constant.

Example of what you cannot do with a constant object:

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

// Attempting to reassign the object will result in an error:
car = {type: "Volvo", model: "EX60", color: "red"}; // Error: Assignment to constant variable.

This example clearly shows that any attempt to reassign car to a different object triggers an error because const ensures that the variable car always points to the same object it was initially assigned to. This rule helps prevent bugs by maintaining a consistent reference throughout the lifetime of the application, though it still allows for internal changes to the object's properties.

Difference Between var, let and const

This comparison is presented in a point format for clarity:

  • var
    • Scope: No block scope, only function or global scope.
    • Can Redeclare: Yes, variables can be redeclared within the same scope.
    • Can Reassign: Yes, the value of variables can be changed.
    • Hoisted: Yes, declarations are moved to the top of their containing scope during compilation.
    • Binds this: Yes, when used in a function, var binds to the global context or the function’s context.
  • let
    • Scope: Yes, has block scope, limiting access to the code block in which it's defined.
    • Can Redeclare: No, variables cannot be redeclared within the same scope.
    • Can Reassign: Yes, the value of variables can be changed after initial declaration.
    • Hoisted: No, variables are not hoisted to the top of their block.
    • Binds this: No, does not bind its own this; it inherits this from the enclosing scope.
  • const
    • Scope: Yes, has block scope similar to let.
    • Can Redeclare: No, variables cannot be redeclared within the same scope.
    • Can Reassign: No, the value (or the reference) assigned at declaration is immutable.
    • Hoisted: No, like let, declarations are not hoisted.
    • Binds this: No, does not bind its own this, similarly to let.

This overview provides a clear distinction between the behaviors of var, let, and const, aiding developers in choosing the appropriate declaration type based on the requirements of different use cases in JavaScript programming.

What is Good?

  • let and const have block scope: Accessible only within their defined block, enhancing security and readability.
  • let and const cannot be redeclared: Prevents accidental redeclaration, reducing bugs.
  • let and const must be declared before use: Promotes intentional and clear usage.
  • let and const do not bind to this: They inherit this from their enclosing scope, providing predictability in closures.
  • let and const are not hoisted: Must be declared before use, preventing runtime ordering errors.

What is Not Good?

  • var does not have block scope: It is accessible outside the intended block, which can lead to unexpected behavior.
  • var is hoisted: Declarations move to the top of their scope, which can cause confusion and errors if used before initialization.
  • var binds to this: It can bind to the global context, leading to potential issues in certain contexts.

Browser Support

The let and const keywords, including the first versions of major browsers that provided full support:

  • Google Chrome 49: Full support from March 2016.
  • Microsoft Edge 12: Full support from July 2015.
  • Mozilla Firefox 36: Full support from January 2015.
  • Apple Safari 11: Full support from September 2017.
  • Opera 36: Full support from March 2016.

Note: Both let and const are not supported in Internet Explorer 11 or earlier versions.

Block Scope

When you declare a variable with const, just like with let, it is confined to the block in which it's declared. This means that a variable named x declared inside a block is distinct from any other x declared outside that block.

Example to illustrate block scope with const:

const x = 10; // x declared in the global scope
{
  const x = 2; // This x is local to the block and separate from the global x
}
// The x inside the block does not affect the x outside the block

This example shows that the x inside the block is a completely separate entity from the x outside, ensuring that each block maintains its own scope, enhancing code manageability and preventing unintended interference between variables.

Redeclaring

With var:

  • You can redeclare the same variable using var multiple times anywhere in the same scope.
var x = 2; // Allowed
var x = 3; // Allowed
x = 4;     // Allowed

From var or let to const:

  • Redeclaring a var or let variable as const in the same scope is not allowed.
var x = 2;    // Allowed
const x = 2;  // Not allowed
{
  let x = 2;    // Allowed
  const x = 2;  // Not allowed
}

With const:

  • Redeclaring a const variable within the same scope or block is not allowed
const x = 2;    // Allowed
x = 2;          // Not allowed
var x = 2;      // Not allowed
let x = 2;      // Not allowed
const x = 2;    // Not allowed

Scope Considerations for const:

  • Redeclaring in Different Scopes:
    • You can declare a const variable with the same name in different scopes or blocks.
const x = 2;  // Allowed
{
  const x = 3;  // Allowed
}
{
  const x = 4;  // Allowed
}

These examples illustrate how JavaScript's scoping rules apply to variable declarations with var, let, and const, highlighting the differences in redeclaration capabilities and scope isolation.

Hoisting with var

Variables declared with var are hoisted:

  • This means the declaration (but not the initialization) of var variables is moved to the top of their containing scope.
  • Therefore, you can use var variables before they are explicitly declared in the code.

Example

carName = "Volvo";  // Assigning value before declaration
var carName;        // Declaration is hoisted to the top

Hoisting with const

Variables declared with const are also hoisted:

  • Similar to var, the declaration is hoisted to the top of the scope, but const variables are not initialized.
  • Attempting to use a const variable before its declaration results in a ReferenceError.

Example

alert(carName);         // ReferenceError: carName is not defined
const carName = "Volvo"; // Declaration is hoisted, but no initialization occurs beforehand

This distinction highlights that while both var and const experience hoisting, their behavior upon access before declaration is significantly different. Understanding these differences is crucial for effective JavaScript programming to avoid common errors like ReferenceErrors. For a deeper dive into the nuances of JavaScript hoisting, studying specialized materials on the topic is recommended.

Take a look into your desired course