• JavaScript Basics

  • Operators in JavaScript

  • Conditional Statements in JavaScript

  • JavaScript Strings

  • JavaScript Arrays

  • JavaScript Loop

  • JavaScript Functions

  • Conclusion

JavaScript const

JavaScript const

JavaScript const keyword allows developers to declare variables that cannot be reassigned or redeclared, ensuring that their values remain constant throughout the code. This lesson covers everything you need to know about using const, from its syntax to practical examples.

JavaScript const Key Features:

  • Cannot Be Redeclared: Once a const variable is defined, it cannot be declared again in the same scope.
  • Cannot Be Reassigned: You can’t change the value of a const variable after it’s been set.
  • Block Scope: Like let, const is block-scoped, meaning it is only accessible within the {} block where it is defined.

When to Use JavaScript const?

  • When you have values that should never change.
  • For declaring constants, arrays, objects, functions, or regular expressions that won't be reassigned.

Declaring a const Variable

A const variable must be assigned a value at the time of declaration.

Syntax:

javascript
1const variableName = value;

Example:

javascript
1const PI = 3.14159;
2console.log(PI); // Output: 3.14159

Reassignment and Redeclaration

No Reassignment:

You cannot change the value of a const variable once it has been set.

javascript
1const PI = 3.14;
2PI = 3.15; // Error: Assignment to constant variable

No Redeclaration:

You cannot redeclare a const variable within the same scope.

javascript
1const user = "Alice";
2const user = "Bob"; // Error: Identifier 'user' has already been declared

Block Scope

const variables are block-scoped, meaning they exist only within the block {} where they are declared.

Example:

javascript
1const score = 100;
2
3{
4  const score = 50;
5  console.log(score); // Output: 50
6}
7
8console.log(score); // Output: 100

In this example, the score variable inside the block is separate from the one outside.

Best Practices for Using const

  1. Use const by Default: Whenever possible, use const for variables that do not need to be reassigned.
  2. Use let for Variables that Change: Only use let when you know the variable will be reassigned.
  3. Avoid var: Due to its function scope and hoisting issues, prefer let and const in modern JavaScript.

Frequently Asked Questions