0

If you're creating a new instance of a variable for every scope change/iteration, is it a better practice to use const over let if the variable will not change through re-assignment or be redeclared? Does the circumstance of the variable being inside a loop warrant using let to show intent that there will be multiple variables created with the same name, but in a different scope?

$('.products').each(function() {
  const $product = $(this);

  // Do something with $product
});

Versus:

$('.products').each(function() {
  let $product = $(this);

  // Do something with $product
});
docta_faustus
  • 2,383
  • 4
  • 30
  • 47
  • There's no 'right' answer to this as it's a matter of stylistic opinion, so I'm going to vote to close this. That said, [hopefully this article will help you](https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75) – Rory McCrossan Nov 19 '17 at 18:49
  • That is not generally how someone would choose to interpret `let`. – Oliver Charlesworth Nov 19 '17 at 18:49
  • 1
    It's almost entirely up to you, a matter of opinion, and therefore off-topic for SO. The closest you can get to objective reasons for using `const` here are 1. It documents your intent not to change the variable (for future maintainers, including yourself); 2) If a future maintainer writes code modifying it, it fails early with a clear error; 3) Theoretically, it saves the JavaScript engine the effort to see if you ever modify `$product` before doing optimizations that assume you don't, which is unlikely to be a significant performance factor. – T.J. Crowder Nov 19 '17 at 18:50
  • That's not a loop, that's just a callback, and therefore the decision is the same as in any normal function. – Bergi Nov 19 '17 at 18:51
  • 1
    That duplicate choice is **quite** a stretch (and despite what the stupid message says, no, I didn't vote to close this as a dupe), but since the question needed to be closed (primarily opinion-based) anyway... – T.J. Crowder Nov 19 '17 at 18:53

0 Answers0