When to use const with objects in JavaScript?

后端 未结 5 1203
悲哀的现实
悲哀的现实 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:07

    let and const are meant for type safety. There is no situation where you must use them, but they can be handy and reduce hard to spot bugs.

    One example of a situation where const would be useful for an object that you don't want to turn into another type.

    const x = {"hello":"world"};
    
    // This is OK
    x.hello = "stackoverflow";
    
    // This is not OK
    x = JSON.stringify(x);
    

提交回复
热议问题