Array Method includes (ES7) Sample

Available in Chrome 47+ | View on GitHub | Browse Samples

Background

To determine if an array includes an element, we could use the popular if (arr.indexOf(el) !== -1) pattern which exhibits two problems: It fails to "say what you mean", and also fails for NaN, as indexOf uses Strict Equality Comparison and thus [NaN].indexOf(NaN) === -1.

The new Array.prototype.includes method is an ECMAScript 2016 (ES7) proposal. It can be used to determine whether an array includes a given element in an elegant way.

It compares first arguments to the elements of the array, in ascending order, using the SameValueZero algorithm and if found at any position, returns true; otherwise, false is returned.

The optional second argument fromIndex defaults to 0 (i.e. the whole array is searched). If it is negative, it is used as the offset from the end of the array to compute fromIndex.

Live Output


JavaScript Snippet

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

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