JS Hint: Functions declared within loops & The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype

It’s telling you that this:

for (const key in storedBasketItems) {
  // ...

should be

for (const key in storedBasketItems) {
  if (storedBasketItems.hasOwnProperty(key)) {
    // ...

and that if you use var to declare variables, that it has problems inside loops because var is function-scoped, not block-scoped. (But you look to be using const and let, so this isn’t a problem; this is a false positive by JSHint.)

Another way to avoid the in warning is to iterate over the Object.entries of the object instead:

for (const [key, value] of Object.entries(storedBasketItems)) {
  // do stuff with key and value
}

You could also avoid the scope warning by using loops instead of forEach callbacks, eg, change:

food.forEach(function (food, i) {

to

for (const [i, food] of food.entries()) {

You could also look into ESLint, which I personally find to be significantly more useful than JSHint when improving code quality.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top