0

I have this code:

//...
let kozvetlenFl = []
if (kozvetlenFl.length === 0 || kozvetlenFl.findIndex(feladat => feladat.id === child) === -1) {
  kozvetlenFl.push(
    feladatok.find(feladat => child === feladat.id)
  )
}
//...

What i want to earn with this code is to check if the kozvetlenFl is empty (because first, it is), or if it isn't empty, check for duplicate (the child here is not relevant). If i set OR in an if statement, it checks all the statements, or if the first is true, it executes? Because i get the error: TypeError: Cannot read property 'id' of undefined. Because the kozvetlenFl first is empty. How to solve this problem?

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-circuit_evaluation – 001 May 21 '18 at 16:48
  • Just run the snipped in your question and you'll get your answer. – Titus May 21 '18 at 16:49
  • Still get the error. Even if i changed the code to: `if(kozvetlenFl.length === 0 || (kozvetlenFl.length > 0 && kozvetlenFl.findIndex(feladat => feladat.id === child) === -1))` – Gergő Horváth May 21 '18 at 17:13
  • The error is caused by the code inside the `if` statement not by the `if` statement's condition. That means that the code after `||` is not evaluated. – Titus May 23 '18 at 16:08

0 Answers0