Top 10 ES6 features by example

ES6 features – Despite the fact that the ES6 specification is not new. I believe that many developers are still unfamiliar with it. The major reason is most likely a lack of support in web browsers shortly after the standard was published. The standard has been around for almost six years, and many current web browsers support it. You may use transpilers (like Babel) to convert ES6 sources to ES5 sources during the build process of the application. Even if you (or your clients) don’t use the most recent version of the web browser. It’s past time to take a step ahead and learn ES6.

Hot JavaScript Articles and Information.

const and let keywords ES6 features

Finally!, const allows you to specify constants. Variables can be defined with let. That’s fantastic, but

don't we already have variables in JavaScript? 

True, however, variables defined with var have function scope and are pushed to the top of the stack. It denotes the fact that a variable can be utilized before it is defined. Allow variables and constants to have block scope (i.e., they can’t be used before declaration) and can’t be used before declaration.

Example:

function f() {
  var x = 1
  let y = 2
  const z = 3
  {
    var x = 100
    let y = 200
    const z = 300
    console.log('x in block scope is', x)
    console.log('y in block scope is', y)
    console.log('z in block scope is', z)
  }
  console.log('x outside of block scope is', x)
  console.log('y outside of block scope is', y)
  console.log('z outside of block scope is', z)
}

f()

Output:

x in block scope is 100 
y in block scope is 200 
z in block scope is 300 
x outside of block scope is 100 
y outside of block scope is 2 
z outside of block scope is 3 

Array helper functions

New interesting helper methods have emerged. Which makes working with JS arrays much easier in the majority of instances.

How many times have you used logic such as filtering, determining if some or all elements match the criteria, or converting elements? 

Probably quite frequently. You now have fantastic language features working for you. Here are the most important functions, in my opinion:

  • forEach

For each element of the array, executes the supplied function, providing the array element as an argument.

Example:

var colors = ['red', 'green', 'blue']

function print(val) {
  console.log(val)
}

colors.forEach(print)

Output:

red 
green 
blue 
  • map

Creates a new array with the same amount of members, but the supplied function creates the output elements. It just changes the value of each array element.

Example:

var colors = ['red', 'green', 'blue']

function capitalize(val) {
    return val.toUpperCase()
}

var capitalizedColors = colors.map(capitalize)

console.log(capitalizedColors)

Output:

["RED","GREEN","BLUE"] 
  • filter

Creates a subset of the original array in a new array. The result contains these components that pass the supplied function’s test, which should return true or false.

Example:

var values = [1, 60, 34, 30, 20, 5]

function lessThan20(val) {
    return val < 20
}

var valuesLessThan20 = values.filter(lessThan20)

console.log(valuesLessThan20)

Output:

[1,5] 
  • find

The first element that passes the supplied function’s test, which should return true or false, is found.

Example:

var people = [
  {name: 'Jack', age: 50},
  {name: 'Michael', age: 9}, 
  {name: 'John', age: 40}, 
  {name: 'Ann', age: 19}, 
  {name: 'Elisabeth', age: 16}
]

function teenager(person) {
    return person.age > 10 && person.age < 20
}

var firstTeenager = people.find(teenager)

console.log('First found teenager:', firstTeenager.name)

Output:

First found teenager: Ann 
  • every

Checks if each member of the array satisfies the supplied function’s test, which should return true or false.

Example:

var people = [
  {name: 'Jack', age: 50},
  {name: 'Michael', age: 9}, 
  {name: 'John', age: 40}, 
  {name: 'Ann', age: 19}, 
  {name: 'Elisabeth', age: 16}
]

function teenager(person) {
    return person.age > 10 && person.age < 20
}

var everyoneIsTeenager = people.every(teenager)

console.log('Everyone is teenager: ', everyoneIsTeenager)

Output:

Everyone is teenager:  false 
  • some

Checks if any member of the array satisfies the supplied function’s test, which should return true or false.

Example:

var people = [
  {name: 'Jack', age: 50},
  {name: 'Michael', age: 9}, 
  {name: 'John', age: 40}, 
  {name: 'Ann', age: 19}, 
  {name: 'Elisabeth', age: 16}
]

function teenager(person) {
    return person.age > 10 && person.age < 20
}

var thereAreTeenagers = people.some(teenager)

console.log('There are teenagers:', thereAreTeenagers)

Output:

There are teenagers: true 
  • reduce

Reduces an array to a single value by applying a function given as the first parameter to an accumulator and each element in the array (from left to right). As the second parameter of the reduction function, the accumulator’s initial value should be given.

Example:

var array = [1, 2, 3, 4]

function sum(acc, value) {
  return acc + value
}

function product(acc, value) {
  return acc * value
}

var sumOfArrayElements = array.reduce(sum, 0)
var productOfArrayElements = array.reduce(product, 1)

console.log('Sum of', array, 'is', sumOfArrayElements)
console.log('Product of', array, 'is', productOfArrayElements)

Output:

Sum of [1,2,3,4] is 10 
Product of [1,2,3,4] is 24 

Arrow functions – ES6 features

The implementation of extremely basic functions (such as the previous sum or product) requires a significant amount of boilerplate code. Is there a way to fix this? Yes, simply experiment with arrow functions!

Example 01:

var array = [1, 2, 3, 4]

const sum = (acc, value) => acc + value
const product = (acc, value) => acc * value

var sumOfArrayElements = array.reduce(sum, 0)
var productOfArrayElements = array.reduce(product, 1)

Arrow functions can also be inline. It really simplifies the code:

Example 02:

var array = [1, 2, 3, 4]

var sumOfArrayElements = array.reduce((acc, value) => acc + value, 0)
var productOfArrayElements = array.reduce((acc, value) => acc * value, 1)

Arrow functions can also be more complex and have many lines of code:

Example 03:

var array = [1, 2, 3, 4]

const sum = (acc, value) => {
  const result = acc + value
  console.log(acc, ' plus ', value, ' is ', result)
  return result
}

var sumOfArrayElements = array.reduce(sum, 0)

Classes – ES6 features

When transitioning from a Java project to a JS project.

Which Java developer doesn't miss classes? Who doesn't prefer explicit inheritance, such as that used in the Java programming language, over creating magic code for a prototypal inheritance? 

Despite the protests of certain JS developers, classes have been introduced in ES6. They don’t change the idea of inheritance in any way. They’re just prototypal inheritance’s syntactic sugar.

Example:

class Point {
    constructor(x, y) {
        this.x = x
        this.y = y
    }

    toString() {
        return '[X=' + this.x + ', Y=' + this.y + ']'
    }
}

class ColorPoint extends Point {
    static default() {
        return new ColorPoint(0, 0, 'black')
    }

    constructor(x, y, color) {
        super(x, y)
        this.color = color
    }

    toString() {
        return '[X=' + this.x + ', Y=' + this.y + ', color=' + this.color + ']'
    }
}

console.log('The first point is ' + new Point(2, 10))
console.log('The second point is ' + new ColorPoint(2, 10, 'green'))
console.log('The default color point is ' + ColorPoint.default())

Output:

The first point is [X=2, Y=10] 
The second point is [X=2, Y=10, color=green] 
The default color point is [X=0, Y=0, color=black] 

Enhanced object literals

Object literals have been enhanced. Now we can much more easily:

  • define-fields with variable assignment of the same name
  • define-functions
  • define-dynamic (calculated) properties

Example:

const color = 'red'
const point = {
  x: 5,
  y: 10,
  color,
  toString() {
    return 'X=' + this.x + ', Y=' + this.y + ', color=' + this.color
  },
  [ 'prop_' + 42 ]: 42
}

console.log('The point is ' + point)
console.log('The dynamic property is ' + point.prop_42)

Output:

The point is X=5, Y=10, color=red 
The dynamic property is 42 

Template strings

Who like concatenating big strings and variables? 

I feel we are in the minority. Who doesn’t dislike reading it? Everyone, I’m sure. Fortunately, ES6 offers string templates with placeholders for variables that are quite simple to utilize.

Example:

function hello(firstName, lastName) {
  return `Good morning ${firstName} ${lastName}! 
How are you?`
}

console.log(hello('Ranjeet', 'Andani'))

Output:

Good morning Ranjeet Andani! 
How are you? 

Please note, that we can write multi-line text.

Important: Use backticks rather than apostrophes to wrap the text.

Default function arguments

Don’t you like providing all likely function parameters? Use defaults.

Example:

function sort(arr = [], direction = 'ascending') {
  console.log('I\'m going to sort the array', arr, direction)
}

sort([1, 2, 3])
sort([1, 2, 3], 'descending')

Output:

I'm going to sort the array [1,2,3] ascending 
I'm going to sort the array [1,2,3] descending 

Rest and spread operators

  • spread

It enables the extraction of array or object content as single elements.

Example — make a shallow copy of array:

var array = ['red', 'blue', 'green']
var copyOfArray = [...array]

console.log('Copy of', array, 'is', copyOfArray)
console.log('Are', array, 'and', copyOfArray, 'same?', array === copyOfArray)

Output:

Copy of ["red","blue","green"] is ["red","blue","green"] 
Are ["red","blue","green"] and ["red","blue","green"] same? false 

Example — merge arrays:

var defaultColors = ['red', 'blue', 'green']
var userDefinedColors = ['yellow', 'orange']

var mergedColors = [...defaultColors, ...userDefinedColors]

console.log('Merged colors', mergedColors)

Output:

Merged colors ["red","blue","green","yellow","orange"] 
  • rest

Would you like to use an array to tie the first few function arguments to variables and the rest to single variables? You can do that now with relative ease.

Example:

function printColors(first, second, third, ...others) {
  console.log('Top three colors are ' + first + ', ' + second + ' and ' + third + '. Others are: ' + others)
}
printColors('yellow', 'blue', 'orange', 'white', 'black')

Output:

Top three colors are yellow, blue and orange. Others are: white,black 

Destructuring

  • Of array

Allows for the extraction of preferred items from an array and their assignment to variables.

Example:

function printFirstAndSecondElement([first, second]) {
    console.log('First element is ' + first + ', second is ' + second)
}

function printSecondAndFourthElement([, second, , fourth]) {
    console.log('Second element is ' + second + ', fourth is ' + fourth)
}

var array = [1, 2, 3, 4, 5]

printFirstAndSecondElement(array)
printSecondAndFourthElement(array)

Output:

First element is 1, second is 2 
Second element is 2, fourth is 4 
  • Of object

Allows you to extract specified attributes from an object and assign them to variables with the same name as the requested properties.

Example:

function printBasicInfo({firstName, secondName, profession}) {
	console.log(firstName + ' ' + secondName + ' - ' + profession)
}

var person = {
  firstName: 'John',
  secondName: 'Smith',
  age: 33,
  children: 3,
  profession: 'teacher'
}

printBasicInfo(person)

Output:

John Smith - teacher 

Promises

Promises (yeah, I know it sounds strange) that you will get in the future as a result of postponed or long-running tasks.

Promise has two channels: one for outcomes and another for possible errors. The callback function is passed as the ‘then’ function argument to obtain the outcome. You use the callback function as the ‘catch’ function argument to manage errors.

Because of the random function call, the outcome of the example may vary for each iteration.

Example:

function asyncFunc() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
          const result = Math.random();
          result > 0.5 ? resolve(result) : reject('Oppps....I cannot calculate')
        }, 1)
    });
}

for (let i=0; i<10; i++) {
	asyncFunc()
    	.then(result => console.log('Result is: ' + result))
    	.catch(result => console.log('Error: ' + result))
}

Output:

Result is: 0.7930997430022211 
Error: Oppps....I cannot calculate 
Result is: 0.6412258210597288 
Result is: 0.7890325910244533 
Error: Oppps....I cannot calculate 
Error: Oppps....I cannot calculate 
Result is: 0.8619834683310168 
Error: Oppps....I cannot calculate 
Error: Oppps....I cannot calculate 
Result is: 0.8258410427354488 

That’s all for this article if you have any queries please contact us through our website or email us at [email protected]

Leave a Comment