When to use const with objects in JavaScript?

后端 未结 5 1209
悲哀的现实
悲哀的现实 2020-11-30 03:32

I recently read about ES6 const keyword and I can understand its importance when having something like this:

(function(){
    const PI = 3.14;
          


        
5条回答
  •  佛祖请我去吃肉
    2020-11-30 04:19

    it is a common misconception around the web, CONST doesn't creates immutable variables instead it creates immutable binding.

    eg.

     const temp1 = 1;
     temp1  = 2 //error thrown here.
    

    But

     temp1.temp = 3 // no error here. Valid JS code as per ES6
    

    so const creates a binding to that particular object. const assures that variable temp1 won't have any other object's Binding.

    Now coming to Object. we can get immutable feature with Object by using Object.freeze

    const temp3 = Object.freeze( {a:3,b:4})
    temp3.a = 2 // it wont update the value of a, it still have 3
    temp3.c = 6 // still valid but wont change the object
    

提交回复
热议问题