1

Why forEach doesn't work for the following? I tried it a few times and it always return "unexpected token".

// for loop
for(item in items){
        if (items[item].id===idNum){
            console.log(items[item]);
        }
    }

// the for loop works. 

// forEach()

items.forEach(item=>if(item.id===idNum){console.log(item)})
// this returned error message "unexpected token"
4
  • 5
    Because you can not forEach an object. This is part of the Array.prototype. You can Object.keys(items).forEach( instead. Commented Feb 4, 2019 at 16:47
  • what does items look like? Commented Feb 4, 2019 at 16:48
  • 7
    The error comes from an invalid arrow function structure, though. Commented Feb 4, 2019 at 16:49
  • 2
    item=>if(item.id===idNum){console.log(item)} that if is not an expression, you can't use it there. It should be something like (item) => {if ... } Commented Feb 4, 2019 at 16:50

2 Answers 2

4

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement

reference :- Arrow function body

Because this syntax is not correct.

items.forEach(item=>if(item.id===idNum){console.log(item)})

You need to use {} here

items.forEach(item=>{
if(item.id===idNum){console.log(item)}
})
Sign up to request clarification or add additional context in comments.

Comments

0

You have to use brackets for function body:

let items = [ {id:1}, {id:2} ];
let idNum = 2;

items.forEach(item => {
  if (item.id === idNum) { console.log(item) }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.