ECMAScript 2016, also known as ES7, is the seventh version of the ECMAScript standard for JavaScript. It was released in June 2016 and introduced several new features that have helped make JavaScript more expressive and efficient. In this article, we will explore some of the key features of ECMAScript 2016 and provide examples of how they can be used.
Array.prototype.includes()
The includes()
method is a new addition to the Array
prototype object in ECMAScript 2016. It returns a boolean value indicating whether the array includes a certain value, rather than returning the index of that value as indexOf()
does. Here is an example:
const arr = [1, 2, 3, 4, 5];
console.log(arr.includes(3)); // true
console.log(arr.includes(6)); // false
Exponentiation Operator
The exponentiation operator, **
, allows you to calculate the result of raising a number to a certain power. It's a shorthand for using the Math.pow()
method. Here's an example:
const base = 2;
const exponent = 3;
console.log(base ** exponent); // 8
Object.values() and Object.entries()
ECMAScript 2016 introduced two new methods for working with objects: Object.values()
and Object.entries()
. Object.values()
returns an array of the values of an object's own enumerable properties. Object.entries()
returns an array of the object's own enumerable key-value pairs. Here are some examples:
const obj = { x: 1, y: 2, z: 3 };
console.log(Object.values(obj)); // [1, 2, 3]
console.log(Object.entries(obj)); // [["x", 1], ["y", 2], ["z", 3]]
Async/Await
Async/await is a new way to write asynchronous code in ECMAScript 2016. It provides a cleaner and more readable syntax for working with promises. The async
keyword is used to define a function as asynchronous, and the await
keyword is used to wait for a promise to be resolved before continuing. Here's an example:
async function getData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
return data;
}
getData().then(data => console.log(data));
Array.prototype.flat() and Array.prototype.flatMap()
The flat()
and flatMap()
methods were introduced in ECMAScript 2019 (ES10), but were proposed as part of ECMAScript 2016. The flat()
method flattens nested arrays into a single-dimensional array. The flatMap()
method combines the functionality of map()
and flat()
. Here are some examples:
const arr1 = [1, 2, [3, 4]];
console.log(arr1.flat()); // [1, 2, 3, 4]
const arr2 = [1, 2, 3];
console.log(arr2.flatMap(x => [x * 2])); // [2, 4, 6]
Conclusion
ECMAScript 2016 introduced some powerful new features to the JavaScript language. The Array.prototype.includes()
method, exponentiation operator, and Object.values()
and Object.entries()
methods make it easier to work with arrays and objects. Async/await simplifies asynchronous programming, and Array.prototype.flat()
and Array.prototype.flatMap()
provide powerful array