1

i was traying to do the odin project exercises of javascript,

when I execute this line in the console 2 in [2,3,4,5] it gives true

but when I execute 3 in [3,4,5] in the console it gives back false I think it should also be true!!!

any explanation please thank you in advance

1
  • 5
    I don't think in means what you think it means - it's not looking for a value, but a property (or index). Seems like you might want Array.includes() Commented Feb 10, 2023 at 22:02

2 Answers 2

2

The in operator checks if a property key exists on an object. You can think of this array as having 4 keys.

const arr = [2, 3, 4, 5];
// arr has the keys `0`, `1`, `2`, and `3`.
console.log(arr[0], arr[1], arr[2], arr[3]);

So when you have the expression 2 in arr, you are checking if the array has a key 2, not if the value 2 exists in the array.

If you do want to check if an array contains an item, the includes() method would achieve what you want.

const arr = [2, 3, 4, 5];
arr.includes(2); // true
arr.includes(0); // false
Sign up to request clarification or add additional context in comments.

1 Comment

now I get it, thank you so much
1

It behaves like this because the in operator returns true if the specified property (not value) is in the specified object.

So in the first case the array has a length of 4 with indices 0,1,2,3 so the element with the index 2 exists.

In the second case there are 3 elements with indices 0,1,2, so there is no element with an index 3 that is why it returns false.

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.