JS: const Declaration
New in JS2015.
const Declaration
const
is for declaring constants.
It's similar to let Declaration, except you can't change its value once set.
const name = val;
-
declare and assign.
/* variable declared with const cannot be changed */ const x = 3; x = 4; /* TypeError: Assignment to constant variable. */
const name1 = val1, name2 = val2, etc;
-
declare and assign multiple constants, separated by comma.
const Must Have a Value When Declared
const
must have a value when declared.
/* const must have a value */ const x; x = 3; /* error: Uncaught SyntaxError: Missing initializer in const declaration const x; SyntaxError: Missing initializer in const declaration */
Constant of Array
if a Array value is declared constant, the array itself can still change. Because the value is a reference to the object and changing element or length does not change the reference.
const xx = []; xx.push(1); console.log(xx); // [ 1 ]
Constant of Object
If a Object
value is declared const
, you can still add/delete/change properties of the object.
Because the value is a reference to the object, and that does not change when you change properties.
/* if object is declared constant, the object properties can still be modified */ const jj = {}; jj.aa = 3; console.log(jj); // { aa: 3}
No Name Hoisting
The const
doesn't have name hoisting as var
does.
That means, you can't use the name before its const
declaration.
γsee var Declaration Order (Name Hoisting)γ