lab-antwerp-1 / home

https://lab-antwerp-1.github.io/home/randomizer
MIT License
3 stars 13 forks source link

A `for...in` statement with `const` #231

Open AlinaTaoRao opened 2 years ago

AlinaTaoRao commented 2 years ago
const menagerie = {
  swimming: 'mackerel',
  flying: 'crane',
  running: 'cheetah',
  jumping: 'spider',
};
for (const key in menagerie) {
  const value = menagerie[key];
  console.log('-' + value);
}

In the code above, a different property name is assigned to key on each iteration. Since key is declared with const, How can the statements worked with const? Will it be a better practice to use let?

colevandersWands commented 2 years ago

Good question @AlinaTaoRao, it works with const because the old block scope is erased and a new one is created each time through the loop. You can see this pretty well in JS Tutor.

You also know it works because there are no errors when the code runs. If JavaScript will let you use const then it's best to use const

AlinaTaoRao commented 2 years ago

Thanks for answers @colevandersWands . Now I know that const work well at least with for ...of and for ...in statements. Use const as much as I can instead of let in js. 😃

colevandersWands commented 2 years ago

"use const whenever JS will let you". That's a nice little quote about it.

But it's also preference, I'm suggesting you do this for now because it's an easy rule to follow and so everyone's code in class is the same. When you take a job you will want to follow the conventions of that codebase (like the article suggests)

AlinaTaoRao commented 2 years ago

👍 . I'm trying...