Execute Program

JavaScript Arrays: Includes

Welcome to the Includes lesson!

JavaScript arrays' "includes" method tells us whether the array includes a given value. It returns a boolean.

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • We can check for whether an array includes a given element.

  • >
    ['a', 'b'].includes('c');
    Result:
    falsePass Icon
  • >
    ['a', 'b'].includes('a');
    Result:
    truePass Icon
  • The .includes method itself is mercifully simple. That's all there is to it!

  • However, we also need to consider an important detail about JavaScript itself. The next example returns a boolean, but it might not be the one that you expect.

  • >
    const user = {name: 'Amir'};
    [{name: 'Amir'}, {name: 'Betty'}].includes(user);
    Result:
    falsePass Icon
  • Why does this return false, when it looks like the array does include {name: 'Amir'}? It's related to how equality works in JavaScript.

  • When we directly ask whether a user is equal to a seemingly-equivalent user, we get the same answer as above.

  • >
    const user1 = {name: 'Amir'};
    const user2 = {name: 'Amir'};
    user1 == user2;
    Result:
    falsePass Icon
  • This happens because the == operator doesn't look inside the objects to check their properties. Instead, == simply asks "are these the same values, stored at the same location in memory?"

  • In the code above, we created the objects separately, so they're two different values stored at two different locations. Many parts of the JavaScript language work in this way: they compare by identity ("are these values stored at the same location in memory?") rather than equality ("would a human say that these values look the same?")

  • Here's that same comparison again, but this time we compare a single object with itself. It's equal to itself and .includes returns true.

  • >
    const user = {name: 'Amir'};
    user == user;
    Result:
    truePass Icon
  • >
    const user = {name: 'Amir'};
    [user, {name: 'Betty'}].includes(user);
    Result:
    truePass Icon
  • This comparison behavior is a deep and general fact about JavaScript, so future lessons won't point out every place where it applies. But keep in mind that comparisons in JavaScript work according to this rule, which is sometimes surprising.