Javascript const Declaration

Introduction

const behaves like let.

const is used to define constant value while let is used to define variable.

We must initialize the constant with a value and that value cannot be changed after declaration.

Attempting to modify a const variable will result in a runtime error.

const age = 26; 
age = 36;  // TypeError: assignment to a constant 
               

const disallows redundant declaration

const name = 'Javascript'; 
const name = 'Java';  // SyntaxError 
            

const is scoped to blocks

const name = 'CSS'; 
if (true) { 
   const name = 'HTML'; 
} 
console.log(name);  // CSS  

We can add property to const object.

const person = {}; 
person.name = 'CSS';  // ok 

The following code shows use cases of const in for loop.

let i = 0; //from w  ww.j a v a2  s  .  c om
for (const j = 7; i < 5; ++i) { 
   console.log(j); 
} 
// 7, 7, 7, 7, 7 

for (const key in {a: 1, b: 2}) { 
   console.log(key); 
} 
// a, b 
            
for (const value of [1,2,3,4,5]) { 
   console.log(value); 
} 
// 1, 2, 3, 4, 5  



PreviousNext

Related