JavaScript const Keyword

前端 未结 8 1654
自闭症患者
自闭症患者 2020-12-09 13:25

Does the const keyword in JavaScript create an immutable reference to immutable data structures? [I\'m assuming that immutable data structures exist in JavaScri

8条回答
  •  自闭症患者
    2020-12-09 14:05

    The only immutable data structure (something that is allocated on heap) is string. All other object alike things like objects, arrays and functions are mutable by default.

    The const creates immutable variable. Yes, "const variable" sounds controversial but that is closest term I can come up with for JS.

    The const content cannot be changed outside of its declaration. But it may contain reference, for example, to the object that is mutable by itself. So you can modify its properties through that const reference to it.

    And if you want to make object to be immutable then there is a Object.freeze(obj) method.

提交回复
热议问题