Js Const in JavaScript
? JavaScript const
What is const?
constdeclares a block-scoped constant variable.The variable must be initialized when declared.
Its binding cannot be reassigned after initialization.
Basic Example
const PI = 3.14159;console.log(PI); // 3.14159// Trying to reassign throws an error// PI = 3.14; // TypeError: Assignment to constant variable.Important Details
constmeans the binding (variable reference) is constant, not the value itself.For objects and arrays, you can modify their contents, but cannot reassign the variable.
const arr = [1, 2, 3];arr.push(4); // Allowedconsole.log(arr); // [1, 2, 3, 4]// arr = [5, 6]; // Error: Assignment to constant variable.const vs let vs var
| Keyword | Scope | Reassignable | Hoisting behavior |
|---|---|---|---|
const | Block-scoped | No | No, not usable before declaration |
let | Block-scoped | Yes | No, not usable before declaration |
var | Function-scoped | Yes | Yes, undefined before assignment |
When to Use const
Use
constby default.Use
letonly if the variable value will change.Avoid
varin modern JS.
Want me to show you examples of scope differences or how to safely use const with objects and arrays?