What is the const keyword in JavaScript?
var, let, and const are probably the first words you hear about while learning JavaScript. Since the let keyword has been already explained in this Answer, and var doesn’t deserve a separate article yet, let’s find out what const is:
const
constis a JavaScript keyword introduced by ES6 that doesn’t have a previous equivalent.
let x = 10;
const x = 10; //This is not possible.
constcreates block-scoped and read-only reference that cannot be reassigned.
const x = 10;x = 15;console.log(x); //This is will throw an error because//x is read-only
- It is a good practice to write
constidentifiers in all-uppercase (to vary them fromletvariables).
const TEMP_X = 10;
- A value assigned to the
constkeyword has to be initialized immediately. Aconstkeyword without an assigned value will cause a syntax error.
const X; //This is not possible.