When to use const with objects in JavaScript?

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

    If you work with an object and want to make sure that identity of the object is never changed say:

    const a = {};
    
    a.b = 1;
    
    // ... somewhere in the other part of the code or from an async call
    // suddenly
    
    someAjaxCall().then(() => { a = null; }) // for preventing this
    

    Also using const is a good hint for javascript compiler to make optimisations about your code, thus making execution much faster then with let or var because the identity never changes,

    BUT

    beware of using const/let in loops for performance reasons, because it might slowdown the performance due to creation of a variable per loop, but in most cases the difference is negligible.

提交回复
热议问题