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

后端 未结 3 1106
北荒
北荒 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:00

    You can use const, but you have to run node on --harmony

    node app.js --harmony
    

    You also have to set "use strict", otherwise you'll have run-time execution issues:

    exports.getQuotation = function(value) {
        "use strict";
    
        const I_AM_CONSTANT = {};
        let quotation = {};
        ...
    

    Other than that, yes if you are running node on --harmony, semantically it makes more sense to use const for constants. For actual variables you should use let instead of var, as let only defines the variable in the scope (avoids hoisting issues)

提交回复
热议问题