Skip to content
Advertisements

Array includes()

JavaScript Array includes() Definition

The includes () method scans the elements inside the array. This search result returns the value “true” if the element is found in the array. If the element is not in the array, it returns “false“.

array.includes(element, start)

element (required) :The item to be searched is specified here.
start (optional) : At which position in the array to start the search. Default 0.


Let’s see how it works with a small example:

        let names = ["abby", "brisa", "bob", "alice"];

        let process = names.includes("abby");

        console.log(process)

True

As shown in the example above, if the searched element is in the array, it returns “true”.

Returns “false” if the searched element is not in the array. Let’s see an example:

        let names = ["abby", "brisa", "bob", "alice"];

        let process = names.includes("alex");

        console.log(process)

False


Includes() vs indexOf()

The includes () method results in a boolean value. But the indexOf () method does not result in a “boolean” value. The indexOf () value returns its order after it finds the element.

        let names = ["abby", "brisa", "bob", "alice"];
        let process1 = names.includes("bob");
        let process2 = names.indexOf("bob");
        console.log(process1)
        console.log(process2)

True
2


JavaScript Array includes() Examples

Example 1

        let process1 = list.includes("zero", 0);
        let process2 = list.includes("first", 1);
        let process3 = list.includes("second", 2);
        let process4 = list.includes("third", 3);

        console.log(process1);
        console.log(process2);
        console.log(process3);
        console.log(process4);

output:

true
true
true
true

We can use includes () this way.

        let process1 = list.includes("first", 0);
        let process2 = list.includes("zero", 1);
        let process3 = list.includes("third", 2);
        let process4 = list.includes("second", 3);

        console.log(process1);
        console.log(process2);
        console.log(process3);
        console.log(process4);

output:

false
false
false
false


Example 2

        var basketOfApples = ['🍎', '🍏', '🍎', '🍏', '🌰', '🍎', '🍏'];
        if (basketOfApples.includes('🌰')) {
            console.log('Your basket of apples contains a chestnut.');
        }
        // The old way still "works"...
        if (basketOfApples.indexOf('🌰') !== -1) {
            console.log('Your basket of apples contains a chestnut.');
        }

        var buildingInFire = [' ', ' ', '🔥', '🔥', '🔥', ' '];
        if (buildingInFire.includes('🔥', 3)) {
            console.log('A fire is burning after the 3rd floor.');
        }
        if (buildingInFire.includes('🔥', -2)) {
            console.log('A fire is burning in the last 2 floors.');
        }

output:

Your basket of apples contains a chestnut.
Your basket of apples contains a chestnut.
A fire is burning after the 3rd floor.
A fire is burning in the last 2 floors.

Source of this code:https://googlechrome.github.io/samples/array-includes-es7/


Polyfill

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(valueToFind, fromIndex) {

      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(valueToFind, elementK) is true, return true.
        if (sameValueZero(o[k], valueToFind)) {
          return true;
        }
        // c. Increase k by 1. 
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

Browser Support

Chrome47
Edge14
Firefox43
Internet Explorerno
Opera34
Safari9
Android webviewyes
Chrome for Androidyes
Edge mobile14
Firefox for Android43
Opera Android34
Advertisements

2 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: