0

Recently I was surprised that both of these code blocks work just fine (see snippet):

for (let propName in myObject) {
  console.log(propName);
}

for (const propName in myObject) {  // A const THAT WILL CHANGE VALUE ?
  console.log(propName);
}

It seems like I'm using a const that it's changing value.

QUESTION

How can this be possible and is one better than the other? Regarding memory allocation and performance?

const myObject = {
  propA: 'foo',
  propB: 'bar'
};

console.log('For in with let:');

for (let propName in myObject) {
  console.log(propName);
}

console.log('For in with const:');

for (const propName in myObject) {
  console.log(propName);
}
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
  • _It seems like I'm using a const that it's changing value._ No. That's now how `const` works in a for loop. **Each element looped** is assigned to a **readonly variable**, it's not **one** readonly variable, it's just that **each** element looped in the for is readonly, this is actually different from reassigning the same variable. – briosheje Jul 04 '19 at 10:35
  • But it does not work in a regular for loop. How is it different? – cbdeveloper Jul 04 '19 at 10:36
  • 1
    You can find the answer in the linked question, it's actually very different, since the regular for declaration is evaluated only once **before** the loop body is executed. – briosheje Jul 04 '19 at 10:38
  • 1
    @cbdev420 - In a simple `for` loop, the iterator variable gets modified by the increment section of the loop structure. In a `for-in` or `for-of`, it doesn't (there is no increment section). This may help: https://pastebin.com/ZHC1WFZs – T.J. Crowder Jul 04 '19 at 10:38
  • @T.J.Crowder Thanks! Should I choose one over the other? Is there a difference performance-wise? – cbdeveloper Jul 04 '19 at 10:41
  • 1
    @cbdev420 - You mean `const` vs. `let`? I'd be truly shocked if there were a performance difference that would have a measurable impact on real-world code. I suppose *in theory* declaring it `const` would make it more cacheable or something, but I'd expect the JavaScript engine to detect you never assign to it and handle it as const even if declared with `let`. So it's more of a style question. I use `const` any time I don't intend to change the value of a variable, so that if I do try to assign to it, my IDE (or if I don't notice, the JS engine itself) tells me I'm trying to change it. :-) – T.J. Crowder Jul 04 '19 at 11:24
  • @T.J.Crowder Thanks a lot! I'll adopt that good practice! – cbdeveloper Jul 04 '19 at 11:26

0 Answers0