Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a constant in javascript

I'm designing some classes and for some data I want to use fields that are constant.

Now, AS USUAL, IE does not support the key const so

const T = 10;

not work.

I could create a property via __defineGetter__ and __defineSetter__ to mime that but , AS USUAL, IE does not support that syntax (IE 8 has Object.defineProperty but not work on custom object).

Any idea?

like image 800
xdevel2000 Avatar asked Jul 14 '09 13:07

xdevel2000


People also ask

How do you create a constant in JavaScript?

ES6 provides a new way of declaring a constant by using the const keyword. The const keyword creates a read-only reference to a value. By convention, the constant identifiers are in uppercase. Like the let keyword, the const keyword declares blocked-scope variables.

How do you declare a constant?

You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.

What is a constant in JavaScript?

Constants are immutable variables which value cannot be changed. Once, you have created a constant, its value cannot be changed. While coding in JavaScript, many times you may have come across a requirement to create constants.

Which keyword creates a constant in JavaScript?

The const keyword was introduced in ES6 (2015). Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned. Variables defined with const have Block Scope.


2 Answers

Old question but nowadays you can simply use:

const MY_CONST = 10;

From MDN:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

Supported by all the main browsers already.

like image 52
Jaqen H'ghar Avatar answered Oct 21 '22 07:10

Jaqen H'ghar


There is a freeze() method in Javascript which can be used to create actual constants.

Usage:

    var consts = {};                    // Object to store all constants
    consts.MY_CONSTANT= 6;
    Object.freeze(consts);              // Make the consts truly read only
    consts.MY_CONSTANT= 7;              // Trying to do this will give error
like image 22
kaushal Avatar answered Oct 21 '22 05:10

kaushal