In javascript should I use const instead of var whenever possible?

后端 未结 3 1124
北荒
北荒 2021-02-20 05:31

If creating a reference to an object, and the reference is not going to change (even though the object will), is it better to use const instead of var?

For example:

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-20 06:02

    If you check MDN, for its reference you can find that its an experimental technology which is part of ES6 proposal. Its browser support is limited.

    Reference for const from MDN

    This is an experimental technology, part of the Harmony (ECMAScript 6) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

    So this answers whether you should use everywhere. :)

    Also if you want to create properties in objects which should not be allowed to change, then you should check Object.defineProperties() and the use of writable attribute.

提交回复
热议问题