最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ESLint error: 'value' is never reassigned use 'const' instead - Stack Overflow

programmeradmin1浏览0评论

I'm adding ESLint to my Node project and cannot figure out how to change this code to work properly:

const connection = {};

for (let [prop, value] of connectionString) {
  prop = prop.split(' ')[0];
  connection[prop] = value;
}

I'm getting error:

'value' is never reassigned. Use 'const' instead.

I'm adding ESLint to my Node project and cannot figure out how to change this code to work properly:

const connection = {};

for (let [prop, value] of connectionString) {
  prop = prop.split(' ')[0];
  connection[prop] = value;
}

I'm getting error:

'value' is never reassigned. Use 'const' instead.

Share Improve this question edited Oct 28, 2019 at 7:33 CertainPerformance 372k55 gold badges352 silver badges357 bronze badges asked Oct 28, 2019 at 7:27 WebJuniorWebJunior 131 silver badge4 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

Rather than reassigning prop, create a new variable for the first word. That way, both prop and value can be declared with const:

const connection = {};
for (const [prop, value] of connectionString) {
  const firstWord = prop.split(' ')[0];
  connection[firstWord] = value;
}

Most of the time, clean readable code can work just fine without ever reassigning a variable. Best to only reassign an existing variable when you absolutely have to - that's a big part of why the rule exists, to prod you to use const (and produce more readable code as a result).

You could also achieve it without the intermediate variable:

const connection = {};
for (const [prop, value] of connectionString) {
  connection[prop.split(' ')[0]] = value;
}
发布评论

评论列表(0)

  1. 暂无评论