Language: EN

javascript-declarar-constantes-con-const

What are constants and how to use them in JavaScript

A constant in JavaScript is a variable that cannot be reassigned after its initialization.

This means that once a value has been assigned to a constant, that value cannot be changed during the execution of the program. This prevents potential mistakes and improves code maintainability.

In JavaScript, constants are declared using the const keyword, which was introduced in ECMAScript 6 (2015).

Declaring constants

The basic syntax for declaring a constant in JavaScript is as follows:

const CONSTANT_NAME = value;

For example,

const PI = 3.14159;
const API_URL = "https://api.example.com/data";

In these examples,

  • PI and API_URL are constants
  • If we try to reassign a new value to these constants, it will generate an error

Using constants with primitive types

Constants can be used with any primitive type in JavaScript (such as numbers, strings, booleans).

const MAX_USERS = 100;
const WELCOME_MESSAGE = "Welcome to the JavaScript course";
const IS_ADMIN = true;

Using constants with objects and Arrays

Although its name can be misleading, do not confuse constant with immutable. const ensures that the value of a variable cannot be changed after its assignment.

However, if the variable is a reference (like an object or an array) the properties or elements of that object or array can be modified.

Let’s see it with an example,

const user = {
  name: "Juan",
  age: 30
};

// Trying to reassign the object
user = { name: "María", age: 25 }; // This will generate an error

// Modifying a property
user.age = 31; // This is valid

In the example,

  • We CANNOT reassign the user object because it is constant
  • But NOTHING PREVENTS us from modifying its members.

Similarly, in an array

const numbers = [1, 2, 3, 4, 5];

// Trying to reassign the array
numbers = [10, 20, 30]; // This will generate an error

// Modifying an element
numbers[0] = 10; // This is valid

// Adding a new element
numbers.push(6); // This is valid
  • We CANNOT reassign the numbers object
  • But NOTHING PREVENTS us from modifying its elements

This is how references work in programming
if you have questions, check the Introduction to Programming Course read more ⯈

Constants in the block context

Constants, like variables declared with let, have block scope. This means that a constant is only available within the block in which it is declared.

if (true) {
  const MESSAGE = "Hello World";
  console.log(MESSAGE); // "Hello World"
}
console.log(MESSAGE); // Error: MESSAGE is not defined

Additionally, they are also subject to the TDZ (Temporal Dead Zone). This means that they cannot be accessed before their declaration in the code.

console.log(GREETING); // Error: Cannot access 'GREETING' before initialization
const GREETING = "Hello";