ES7 & ES8 Features

ES7 (ES2016) features

Array.prototype.includes()

  • Replacement of indexOf
  • Returns boolean instead of index position
  • Works with NaN
  • Optimisation support using fromIndex arg
const arr = ['react', 'angular', 'vue']
// WRONG
if (arr.indexOf('react')) { // 0 -> evaluates to false, definitely as we expected
  console.log('Can use React') // this line would never be executed
}
// Correct
if (arr.indexOf('react') !== -1) {
  console.log('Can use React')
}
if (arr.includes('react')) {
  console.log('Can use React')
}

console.log([1, 2, NaN].includes(NaN)) // true
console.log([1, 2, -0].includes(+0)) // true
console.log(['a', 'b', 'c'].includes('a')) // true
console.log(['a', 'b', 'c'].includes('a', 1)) // false

Exponentiation Operator

  • Replacement of Math.pow(2, 3)
  • Useful in case of 3D, Virtual Reality, SVG or data visualization
  • Borrowed from other languages
let a = 7**3 // 343
let b = 2 ** 3 // 8

// operation assignment

let a = 7
a **= 3

console.log(a); // 343

ES8 Features

Object.values & Object.entries

  • Both return arrays just like Object.keys
  • Object.values returns an array of object’s own enumerable property values
  • Object.entries, on the other hand, will return an array of object’s own enumerable property key-value pairs (as an array).
  • Each item of the resulting array will be an array too.
let obj = {a: 1, b: 2, c: 3}
for (let key of Object.keys(obj)) {
  console.log(key, obj[key])
}
Object.values(obj).forEach(value=>console.log(value)) // 1, 2, 3

// or using for of loop

for (let value of Object.values(obj)) {
  console.log(value)
}
let obj = {a: 1, b: 2, c: 3};
JSON.stringify(Object.entries(obj)); // "[["a",1],["b",2],["c",3]]"

String padStart & padEnd

  • padStart() returns a string of a given length (targetLength) by inserting pads at the beginning.
  • padEnd() behaves the same way by appending characters in the end
console.log('react'.padStart(10).length)         // "       react" is 10
console.log('backbone'.padStart(10).length)         // "  backbone" is 10
console.log('backbone'.padEnd(10, '*')); // "backbone**"
let obj = {a: 1, b: 2, c: 3};
JSON.stringify(Object.entries(obj)); // "[["a",1],["b",2],["c",3]]"

Object.getOwnPropertyDescriptors()

console.log('react'.padStart(10).length)         // "       react" is 10
console.log('backbone'.padStart(10).length)         // "  backbone" is 10
console.log('backbone'.padEnd(10, '*')); // "backbone**"
let obj = {a: 1, b: 2, c: 3};
JSON.stringify(Object.entries(obj)); // "[["a",1],["b",2],["c",3]]"
Made with Slides.com