Loading...
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
constvariable is defined, it cannot be declared again in the same scope. - Cannot Be Reassigned: You can’t change the value of a
constvariable after it’s been set. - Block Scope: Like
let,constis 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
1 lines
|7/ 500 tokens
1const variableName = value;
Code Tools
Example:
javascript
2 lines
|14/ 500 tokens
1 2const PI = 3.14159; console.log(PI); // Output: 3.14159
Code Tools
Reassignment and Redeclaration
No Reassignment:
You cannot change the value of a const variable once it has been set.
javascript
2 lines
|18/ 500 tokens
1 2const PI = 3.14; PI = 3.15; // Error: Assignment to constant variable
Code Tools
No Redeclaration:
You cannot redeclare a const variable within the same scope.
javascript
2 lines
|24/ 500 tokens
1 2const user = "Alice"; const user = "Bob"; // Error: Identifier 'user' has already been declared
Code Tools
Block Scope
const variables are block-scoped, meaning they exist only within the block {} where they are declared.
Example:
javascript
8 lines
|29/ 500 tokens
1 2 3 4 5 6 7 8const score = 100; { const score = 50; console.log(score); // Output: 50 } console.log(score); // Output: 100
Code Tools
In this example, the score variable inside the block is separate from the one outside.
Best Practices for Using const
- Use
constby Default: Whenever possible, useconstfor variables that do not need to be reassigned. - Use
letfor Variables that Change: Only useletwhen you know the variable will be reassigned. - Avoid
var: Due to its function scope and hoisting issues, preferletandconstin modern JavaScript.