This is a small function from the latest ES7 release (just one of a small handful of new features compared to the large ES6 array of features). It determines whether an array contains an element and simply returns true or false. See example below:
There were a few ways to do this before, such as using the indexOf function, but it makes code so messy sometimes. Sure, there are even libraries like Lodash which I also love, but having a native feature baked into JS is great.
Polyfill: includes - Mozilla
A much larger and more used feature of modern JS, although it’s specified in the Living Standard from the WHATWG community as opposed to the EMCAScript from Emca International like most other JS features.
Aside from the ugly as hell old style XHR requests, the other popular way of sending requests to the server is via jQuery AJAX. This is often the only feature of jQuery I use nowadays, so the fetch API is great to reduce those kilobytes going over the wire by removing jQuery completely.
The above is a simple example which requests info from a server side PHP page. This response (resp) isn’t a JSON or HTML by default like jQuery AJAX calls. It returns a promise, which then must be converted to the correct format and passed to the next function in the chain with then().
Polyfill: fetch - GitHub
This one is widely used, but I wanted to add it in as it is incredible. Gone are the days of the following when all HTML content is on one line.
Now with multi-line strings, we can simply use back ticks to spread the content over multiple lines:
Simple and effective!
This feature has not yet been completely standardised at the time of writing this but has been around as a draft in evergreen browsers. It’s relatively complicated for the scope of this post so I’ll cover the basics and go into detail another time.
Async/await is about providing asynchronous functionality to JS, similar to that of callbacks and promises. The huge benefit of async/await compared to traditional methods like callbacks is that it looks more like synchronous code, making it more natural to read:
As you can see, it provides a much cleaner and concise way of providing functionallity which would otherwise be something like the below:
While on the topic, another great way of adding asynchronous functionality to JS is via Observables. This is my favorite pattern, and has been used in other languages initially, and eventually bought to JS with the use of RxJS. I discovered it in Angular 2, and it’s excellent! It can provide much more to the developer besides just asynchronous development.
Polyfill: async/await - Babel
That’s it folks! As always, check caniuse before jumping straight into using these in production projects. Most of the time there are decent polyfills of which I’ve added a few above.