[the_ad id=”684″]
Meaning
const is a keyword added in javascript ES6.
const is a short hand for constant and allows declaring constant values in javascript.

Constant values are those which can not be changed after declared once.

const is one of the many features introduced in ES6 such as let, arrow functions etc. This article will explain the usage of const with examples.
Syntax
const keyword is followed by a user defined variable name to declare it as a constant. Example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// declaring a constant integer
const num = 12;
// declaring a constant string
const name = 'codippa';
// declaring a constant integer const num = 12; // declaring a constant string const name = 'codippa';
// declaring a constant integer
const num = 12;
// declaring a constant string
const name = 'codippa';

Name of variable should be as per javascript variable naming rules.
As a naming convention in most programming languages, constants are declared in capital letters. This is a convention, not a rule, you can define it in lower case as well.
Variables declared with const should be initialized at the time of declaration or else there will be an error. Example,
Below statement

const num;

will result in

SyntaxError: Missing initializer in const declaration

So, you need to provide a value to a const variable at the time of declaring it. Above statement can be corrected as

const num = 20;

[the_ad id=”651″] const primitives
Primitive types are those which hold a value such as integers, decimal values, string, boolean etc. Primitives declared with const can not be modified again. Example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// valid
const x = 12;
// error !!
x = 25;
// valid const x = 12; // error !! x = 25;
// valid
const x = 12;
// error !!
x = 25;

will result in

TypeError: Assignment to constant variable.

const Objects
A javascript object declared with const can not be assigned again but you can modify its properties or add new properties to it.
That is, following is not allowed.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// define const object
const obj = {'name': 'codippa'};
// reassign to new object
obj = {'language': 'javascript'};
// define const object const obj = {'name': 'codippa'}; // reassign to new object obj = {'language': 'javascript'};
// define const object
const obj = {'name': 'codippa'};

// reassign to new object
obj = {'language': 'javascript'};

and will result in

TypeError: Assignment to constant variable.

But, this is legal.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// initialize object
const obj = {'device': 'laptop'};
// add properties
obj['brand'] = 'Lenovo';
obj['frequency'] = 2.4;
// update properties
obj['brand'] = 'Sony';
// initialize object const obj = {'device': 'laptop'}; // add properties obj['brand'] = 'Lenovo'; obj['frequency'] = 2.4; // update properties obj['brand'] = 'Sony';
// initialize object
const obj = {'device': 'laptop'};
// add properties
obj['brand'] = 'Lenovo';
obj['frequency'] = 2.4;

// update properties
obj['brand'] = 'Sony';

const Arrays
Similar to objects, a javascript array declared with const can not be re-initialized but you can add or push new elements to it.
Thus,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// define const array
const arr = [2, 4];
// reassign to new array
arr = [];
// define const array const arr = [2, 4]; // reassign to new array arr = [];
// define const array
const arr = [2, 4];

// reassign to new array
arr = [];

is invalid while, this is allowed

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// initialize array
const arr = ['xyz', 'swfd'];
// add elements
arr.push('abcd');
// initialize array const arr = ['xyz', 'swfd']; // add elements arr.push('abcd');
// initialize array
const arr = ['xyz', 'swfd'];
// add elements
arr.push('abcd');

[the_ad id=”644″] Block scope
A const declared in a block is visible only inside that block and you can not modify its value in that block after initialization.
But, outside the block, the variable is not visible and can be re-initialized. Example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// declare a constant
const c = 23;
{
// declare a constant with the same name
const c = 46;
console.log(c) // prints 46
}
// no problem
console.log(c) // prints 23
// declare a constant const c = 23; { // declare a constant with the same name const c = 46; console.log(c) // prints 46 } // no problem console.log(c) // prints 23
// declare a constant
const c = 23;
{
 // declare a constant with the same name
 const c = 46;
 console.log(c)  // prints 46 
}
// no problem
console.log(c)  // prints 23

Above code works perfectly fine. This is because the variable declared inside the curly braces is visible only in that block.
const function
In javascript, a function can be assigned to a variable as shown below.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
f = function() {
console.log('Called');
}
f = function() { console.log('Called'); }
f = function() {
  console.log('Called');
}

Same variable can later be assigned a different function.

But, if the variable is declared using const, then it can not be reassigned a function after it is initialized the first time.
Thus, below code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// assign function to const
const f = function() {
console.log('Called');
}
// reassign function to variable
f = function() {
console.log('Called Again');
}
// assign function to const const f = function() { console.log('Called'); } // reassign function to variable f = function() { console.log('Called Again'); }
// assign function to const
const f = function() {
   console.log('Called');
}

// reassign function to variable
f = function() {
   console.log('Called Again');
}

will result in

TypeError: Assignment to constant variable.

[the_ad id=”656″] const arrow function
Arrow function is a new concept added in javascript ES6 where there is no need to use function keyword while defining functions and there is an arrow(=>) between function parameters and body.
More on arrow functions here.

An arrow function can also be assigned to a variable as

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
f = () => {
console.log('Called');
}
f = () => { console.log('Called'); }
f = () => {
  console.log('Called');
}

Similar to normal functions, if arrow function is assigned to a const variable, you can not reassign it again as shown below.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// assign function to const
const f = () => {
console.log('Called');
}
// reassign function to variable
f = () =>{
console.log('Called Again');
}
// assign function to const const f = () => { console.log('Called'); } // reassign function to variable f = () =>{ console.log('Called Again'); }
// assign function to const
const f = () => {
   console.log('Called');
}

// reassign function to variable
f = () =>{
   console.log('Called Again');
}

This will again be a TypeError.

const Hoisting
Javascript hoisting means you can use a variable declared with var before declaring them. Example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
b = 20;
let b;
console.log(b); // prints 20
b = 20; let b; console.log(b); // prints 20
b = 20;
let b;
console.log(b);   // prints 20

But with const, this is not the case.
That is, you can not use a variable declared with const before declaring. Same code that uses const in place of var as below

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
b = 20;
const b = 10;
console.log(b);
b = 20; const b = 10; console.log(b);
b = 20;
const b = 10;
console.log(b);

gives error

ReferenceError: Cannot access ‘b’ before initialization

[the_ad id=”3385″] const browser support
Minimum browser versions that support const are

Browser Version
Firefox 36
Chrome 21
Edge 12
IE 11
Safari 5.1
Opera 9

Hope the article was useful, click the clap if you liked it.

Categorized in:

Javascript Tutorial,