Data

Constant

JavaScript

 

Defining Constant

ECMAScript 2015
const PI = 3.14;

const E = Math.pow(
    Math.pow(PI,4) + Math.pow(PI,5), 1/6);

const declares a read-only block-scoped reference to a value.

The value should be specified in the const declaration.

While the reference itself is immutable, if constant is pointing to an object, elements inside it can change.

const BITS = [0, 1];

BITS = [0, 0];  // error
BITS[0] = 1;    // BITS -> [1, 1]
 

Defining Constants in one line

ECMAScript 2015
const PI = 3.14, E = 2.71;

You can define multiple constants in one statement.

Here, we are creating constants PI and E.

 

Getting Constant value

ECMAScript 2015
const PI = 3.14;

var r = 2;
var area = r * r * PI;  // area -> 12.56

To get the value of a Constant, you can simply use its name.