const vs let when calling require

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 04:43:28

问题


As io.js now supports ES6 you are finally able to use the const and let keywords. Obviously, let is the successor of var, just with some super-powers.

But what about const? I know, of course, what "constant" means, but I was wondering when to use it (regarding best practices).

E.g., if I create a module that requires another module, I could write:

'use strict';

const util = require('util');

const foo = function () {
  // Do something with util
};

module.exports = foo;

Basically I've replaced every occurence of var with const. Generally speaking, I think that this is okay, but if I follow this pattern, it leaves me with way more uses of const than let, as most variables aren't "variables" in a literal sense.

Is this good style? Should I rather go for let? When should I choose const over let?


回答1:


const can be normally used when you don't want your program

  1. to assign anything to the variable

    "use strict";
    const a = 1;
    a = 2;
    

    will produce TypeError: Assignment to constant variable..

  2. to use the variable without explicitly initializing.

    "use strict";
    const a;
    

    will produce SyntaxError: Unexpected token ;

Simply put, I would say,

  • use const whenever you want some variables not to be modified

  • use let if you want the exact opposite of const

  • use var, if you want to be compatible with ES5 implementations or if you want module/function level scope.

Use let only when you need block level scoping, otherwise using let or var would not make any difference.




回答2:


I have the same feeling that you're describing. A big percentage of declared variables in my code tend to be constant, even objects and arrays. You can declare constant objects and arrays and still be able to modify them:

const arr = [];
arr.push(1);
arr;
// [ 1 ]

const obj = {};
obj.a = 1;
obj;
// { a: 1 }

AFAIK ES6 modules do not require variable declarations when importing, and I suspect that io.js will move to ES6 modules in a near future.

I think this is a personal choice. I'd always use const when requiring modules and for module local variables (foo in your example). For the rest of variables, use const appropriately, but never go mad and use const everywhere. I don't know the performance between let and const so I cannot tell if it's better to use const whenever possible.




回答3:


Performance test const vs let usage on require for Node.js 6.10:

require('do-you-even-bench')([
  { name: 'test 1', fn: function() { 
    const path = require('path');
    } 
  },
  { name: 'test 2', fn: function() { 
    let path = require('path');
    } 
  }
]);

test 1 .... 2,547,746.72 op/s
test 2 .... 2,570,044.33 op/s



来源:https://stackoverflow.com/questions/28135485/const-vs-let-when-calling-require

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!