0

I'm trying understand how the condition myArr[i] works. For some reason it evaluates to false when i is bigger than 2 which also happens to be the length of the array. Apparently myArr[i] is equal to i < myArr.length. Could someone explain?

let myArr = [[1, 3], [5, 2], [2, 1]]

for (let i = 0; myArr[i]; i++){
    console.log(i)  //Result: 0, 1, 2
}

let i = 0
while (myArr[i]){
    console.log(i)  ////Result: 0, 1, 2
    i++
}
1
  • No, it's not equal to i < myArr.length. Try iterating an array like [{}, null, {}] or [true, false, true]. Commented Jan 12, 2020 at 22:03

2 Answers 2

1

When indexing into an array, you will get an undefined result whenever you try an index that doesn't exist. Undefined implicitly converts to a "false-like" value.

Sign up to request clarification or add additional context in comments.

5 Comments

Thx for that quick answer! You're totally right, why didn't I think about that.
You're explenation makes totally sense and when I console log Boolean(myArr[0]) I get "true" but for some reason I get false when I console log myArr[0] == true. Should't that be true?
Well, technically it's not equal to true, it's an array. If you want to convert an object/array's existence to a boolean, here's a little trick: !!myArr[0]
Also, if this answers your question, would you mind marking it as an answer to let people know we're not looking for one anymore?
Sure, I marked it as solved! Thx a lot for your answer and the little trick, exactly what I was looking for. Works like a charm!
0

No myArr[i] is not < the length of the array.

myArry[i] is a reference to whatever is in the memory slot of i Each section of the array is a pointer in memory.

So when you say myArry[2] you are asking the computer to fetch the value stored in the memory of slot 2 in the array. When you say myArry[3] you don't have anything stored in that memory slot, so it returns undefined.

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.