Back to JavaScript
2026-04-145 min read

Constants (JavaScript)

Learn Constants (JavaScript) step by step with clear examples and exercises.

Title: Constants (JavaScript) - Mastering Immutable Variables for Efficient Coding

Why This Matters

In JavaScript, constants are variables that cannot be changed once they have been assigned a value. They are essential for writing cleaner, more efficient, and error-free code by ensuring that certain variables retain their values throughout the execution of a program. Constants are particularly useful in situations where you want to ensure that specific values remain unchanged, such as mathematical constants (like pi), configuration settings, or application identifiers.

Importance of Constants

Using constants can help improve code readability and maintainability by reducing the risk of accidental variable reassignment. This leads to fewer bugs and easier understanding for other developers working on the same project.

Prerequisites

To fully understand this lesson on JavaScript constants, you should have a basic understanding of the following concepts:

  • Variables and assignments in JavaScript
  • Data types in JavaScript
  • Basic JavaScript syntax and semicolons (;)
  • Understanding of objects and arrays
  • Understanding of variable scoping (block vs function)

Importance of Prerequisites

A strong foundation in these concepts is crucial for grasping the concept of constants and their proper usage. If you're unsure about any of these topics, we recommend reviewing them before proceeding with this lesson.

Core Concept

In JavaScript, you can declare a constant using the const keyword. Once declared as a constant, the value assigned to it cannot be changed throughout the lifetime of the variable. Here's an example:

const PI = 3.14;
console.log(PI); // Output: 3.14
PI = 3; // This will result in a TypeError: Assignment to constant variable.

In the above example, PI is declared as a constant and assigned a value of 3.14. Attempting to change its value results in a TypeError because constants are immutable in JavaScript.

Note that that while constants cannot be reassigned, their values can still be used in calculations or assignments to other variables:

const AREA_OF_CIRCLE = PI * Math.pow(RADIUS, 2);
console.log(AREA_OF_CIRCLE); // Output: The area of the circle is calculated correctly using PI

Constants and Objects/Arrays

While you cannot reassign a constant variable directly, you can modify its properties or elements if it's an object or array. For example:

const myObject = { key: 5 };
myObject.key = 10; // This is allowed, but the value of the key in the object is no longer immutable.

In this case, even though we can change the value of myObject.key, the original constant reference remains unchanged.

Constants and Object/Array Immutability

To create truly immutable objects or arrays in JavaScript, you can use third-party libraries such as immutable.js or lodash's _.freeze().

Worked Example

Let's create a simple JavaScript program that calculates the area and circumference of a circle using constants for pi and other variables:

const PI = 3.14;
const RADIUS = 5;

const AREA_OF_CIRCLE = PI * Math.pow(RADIUS, 2);
const CIRCUMFERENCE = 2 * PI * RADIUS;

console.log(`The area of the circle is: ${AREA_OF_CIRCLE}`); // Output: The area of the circle is: 78.53981633974483
console.log(`The circumference of the circle is: ${CIRCUMFERENCE}`); // Output: The circumference of the circle is: 31.41592653589793

Common Mistakes

  1. Assigning a mutable value to a constant:
const myArray = [];
myArray.push(1); // This is allowed, but the array is no longer immutable
myArray = [2]; // This will result in a TypeError: Assignment to constant variable.
  1. Declaring a variable with let or var instead of const:
let myConstant = 5;
myConstant = 10; // This is allowed because it's declared with `let`, not `const`.
  1. Reassigning a constant inside an object or array:
const myObject = {
key: 5
};
myObject.key = 10; // This is allowed, but the value of the key in the object is no longer immutable.

Common Mistakes - Subheadings

  • Improper Use of Constants
  • Misunderstanding of Constant Immutability
  • Using let or var instead of const

Practice Questions

  1. Declare a constant named GRAVITY with a value of 9.8 m/s². What happens when you try to reassign its value?
  2. Write a JavaScript program that calculates the area and perimeter of a rectangle using constants for its length, width, and pi.
  3. Declare an empty array as a constant named myArray. Add an element to the array and explain what happens if you attempt to change the value of myArray itself.
  4. What would happen if you try to declare a function with the const keyword in JavaScript?
  5. Explain the difference between declaring a variable using let, const, and var.
  6. How can you create truly immutable objects or arrays in JavaScript?
  7. What are some best practices for using constants effectively in your code?

FAQ

  1. Can I use const with any data type in JavaScript?

Yes, you can declare constants for any data type in JavaScript, including numbers, strings, objects, and arrays.

  1. What happens if I try to reassign a constant inside an object or array?

While the value of the specific key or element within the object or array can be changed, attempting to change the constant itself (the reference) will result in a TypeError.

  1. Can I use const for function declarations in JavaScript?

No, you cannot declare functions as constants using the const keyword in JavaScript. Functions should be declared using the function keyword or the arrow function syntax (() => {}).

  1. What is the difference between declaring a variable with let, const, and var?
  • let and const are block-scoped variables that can be reassigned within their respective blocks, but const cannot be reassigned at all.
  • var is function-scoped and can be redeclared or reassigned within the same function. This can lead to unexpected behavior and should generally be avoided in favor of let and const.
  1. What are some best practices for using constants effectively in your code?
  • Use meaningful names for your constants.
  • Avoid changing the values of constants if possible, as it can make your code harder to understand.
  • Consider using immutable libraries for truly immutable objects and arrays.
  • Use constants when you want to ensure that specific values remain unchanged throughout your program.
Constants (JavaScript) | JavaScript | XQA Learn