Here are examples of everything new in ECMAScript 2016, 2017, and 2018
It’s hard to keep track of what’s new in JavaScript (ECMAScript). And it’s even harder to find useful code examples.
So in this article, I’ll cover all 18 features that are listed in the TC39’s finished proposals that were added in ES2016, ES2017, and ES2018 (final draft) and show them with useful examples.
This is a pretty long post but should be an easy read. Think of this as “Netflix binge reading.” By the end of this, I promise that you’ll have a ton of knowledge about all these features.
OK, let’s go over these one by one.
1. Array.prototype.includes
includes
is a simple instance method on the Array and helps to easily find if an item is in the Array (including NaN
indexOf
).Trivia: the JavaScript spec people wanted to name itcontains
, but this was apparently already used by Mootools so they usedincludes
.
2.
Exponentiation infix operator
Math operations like addition and subtraction have infix operators like +
-
, respectively. Similar to them, the **
infix operator is commonly used for exponent operation. In ECMAScript 2016, the **
was introduced instead of Math.pow
.1. Object.values()
Object.values()
is a new function that’s similar to Object.keys()
but returns all the values of the Object’s own properties excluding any value(s) in the prototypical chain.
2. Object.entries()
Object.entries()
is related to Object.keys
, but instead of returning just keys, it returns both keys and values in the array fashion. This makes it very simple to do things like using objects in loops or converting objects into Maps.
Example 1:
Example 2:
3. String padding
Two instance methods were added to String — String.prototype.padStart
and String.prototype.padEnd
— that allow appending/prepending either an empty string or some other string to the start or the end of the original string.
'someString'.padStart(numberOfCharcters [,stringForPadding]);
'5'.padStart(10) // ' 5'
'5'.padStart(10, '=*') //'=*=*=*=*=5'
'5'.padEnd(10) // '5 '
'5'.padEnd(10, '=*') //'5=*=*=*=*='
This comes in handy when we want to align things in scenarios like pretty print display or terminal print.
3.1 padStart example:
In the below example, we have a list of numbers of varying lengths. We want to prepend “0” so that all the items have the same length of 10 digits for display purposes. We can use padStart(10, '0')
to easily achieve this.
3.2 padEnd example:
padEnd
really comes in handy when we are printing multiple items of varying lengths and want to right-align them properly.
The example below is a good realistic example of how padEnd
, padStart
, and Object.entries
all come together to produce a beautiful output.
const cars = {
'