Are there constants in JavaScript?

后端 未结 30 2872
抹茶落季
抹茶落季 2020-11-22 08:53

Is there a way to use constants in JavaScript?

If not, what\'s the common practice for specifying variables that are used as constants?

30条回答
  •  一生所求
    2020-11-22 09:36

    JavaScript ES6 (re-)introduced the const keyword which is supported in all major browsers.

    Variables declared via const cannot be re-declared or re-assigned.

    Apart from that, const behaves similar to let.

    It behaves as expected for primitive datatypes (Boolean, Null, Undefined, Number, String, Symbol):

    const x = 1;
    x = 2;
    console.log(x); // 1 ...as expected, re-assigning fails
    

    Attention: Be aware of the pitfalls regarding objects:

    const o = {x: 1};
    o = {x: 2};
    console.log(o); // {x: 1} ...as expected, re-assigning fails
    
    o.x = 2;
    console.log(o); // {x: 2} !!! const does not make objects immutable!
    
    const a = [];
    a = [1];
    console.log(a); // 1 ...as expected, re-assigning fails
    
    a.push(1);
    console.log(a); // [1] !!! const does not make objects immutable
    

    If you really need an immutable and absolutely constant object: Just use const ALL_CAPS to make your intention clear. It is a good convention to follow for all const declarations anyway, so just rely on it.

提交回复
热议问题