ESNext — Array.includes

In our last post, I showed you how to get babel up and running so you can start taking advantage of the cool features of ESNext. The next feature we are going to talk about that is currently part of the 2016 features doesn’t even require that to get it working. That’s because it has come bundled with babel-polyfill and can just be included in your script tags or a require(“babel-polyfill”) in your node.js.

Let’s get started by getting babel-polyfill installed. Get a new directory open and run

npm install babel-polyfill

This should create a directory structure of /node_modules/babel-polyfill/dist/polyfill.js This is the file you pull into a script tag if you want this to work on the browser side. On the node side, all you need is a require(“babel-polyfill”); to make this work.

So, on to Array.includes.

Honestly, I bet a lot of you are surprised that this is not already included in javascript. But, surprise, it is not there yet… But you can totally use it now.

What this essentially looks like is a new method on the Array.prototype that checks the contents of an array. So try out this code…

require(“babel-polyfill”);
var x = [‘1’, ‘Menu’, ‘Top’];
if(x.includes(‘1’)){
console.log(‘I Have it!’); //I have it!
} else {
console.log(‘Its not here!’);
}

Now, this is doing a === not == so there is NO type conversion…

require(“babel-polyfill”);
var x = [‘1’, ‘Menu’, ‘Top’];
if(x.includes(1)){
console.log(‘I Have it!’);
} else {
console.log(‘Its not here!’); //This is what executes…
}

The best part about this 2016 feature is two browsers already have it included. Chrome and Firefox have it included starting with FF45 and CH49.

So, if you are targeting newer browsers, you may be able to use it natively!