10 ES6+ Syntax for writing elegant JavaScript code

Fionna Chan
Level Up Coding
Published in
6 min readMar 25, 2019

--

Not all JavaScript developers get excited when ECMAScript has a new release. It can be annoying to be expected to continually learn new syntax, but it is definitely worth the effort for a smoother development experience. I am surprised by the number of developers around me who haven’t tried out ES6 yet, and so I am here to convince these developers to adopt the new syntax.

There are plenty of articles and tutorials on the full list of ES6 (ES2015). In this article, I would only highlight those I frequently use and introduce several useful syntax updates from ES8 (ES2017) and ES9 (ES2018).

1) Arrow function (ES6)

Arrow functions ()=>{} save us some time from typing function() {}, and it gives us a cleaner look to our files.

const numberOfMealsInThisWeek = [3, 2, 2, 0, 2, 1, 3];
const checkNumberEqualsThree = num => num === 3;
const numberOfDaysWith3Meals = numberList => numberList.filter(checkNumberEqualsThree).length;
numberOfDaysWith3Meals(numberOfMealsInThisWeek);
// output: 2

However, there is one thing to watch out for — it does not behave 100% as function() {} when it is a callback function. The this from the caller is passed into the arrow function lexically, whereas you have to bind this in function() {}. The most popular use case would be the event handler function in a React class component:

// ES5: In your React class component constructor()
this.onChangeHandler = this.onChangeHandler.bind(this);
// ES6: In your React class component constructor()
// you don't have to do anything special
// ES5: In your React class component
// If you don't do .bind(this) in the constructor, it would not work
onChangeHandler(event) {
this.setState({
email: event.target.value
})
}
/* ES6: In your React class component
* This will work perfectly without .bind(this) in the constructor
* Beware that not only are we using ES6 arrow function here,
* we are also using the stage-3 public class fields syntax
* (READ: assigning something to a class field in a Class)
* https://github.com/tc39/proposal-class-fields
*/
onChangeHandler = event => {
this.setState({
email: event.target.value
})
}
// In your React class component render() with either ES6 or ES5
<input name="email" onChange={this.onChangeHandler} />

2) Default parameter values (ES6)

This is extremely handy if you want to call the function with and without arguments.

const hangryMode = (food = 'sushi') => {
console.log('I am so hangry!!! I want ' + food + '!!!');
}
hangryMode();
// output: I am so hangry!!! I want sushi!!!
hangryMode('fish and chips');
// output: I am so hangry!!! I want fish and chips!!!

3) Template literals: String interpolation (ES6)

This is more readable than string concatenations.

const hangryMode = (food = 'sushi') => {
console.log(`I am so hangry!!! I want ${food}!!!`);
}
hangryMode();
// output: I am so hangry!!! I want sushi!!!

And you can have linebreaks within the text to make it a multiline string without typing \n!

const hangryMode = (food = 'sushi') => {
const text = `I am so hangry!!!
I want ${food}!!!`;
console.log(text);
}
hangryMode();
/* output:
* I am so hangry!!!
* I want sushi!!!
*/

Objects

4) Destructure your objects (ES6)

Destructuring saves you many lines on declaring variables. Similarly, you can do the same with arrays.

const travels = {
Apr: 'London',
May: 'Paris',
June: 'Hong Kong'
}
// destructuring them means assigning each value to variables with the name of its key within the scope you declare the below lineconst { Apr, May, June } = travels;
/* this creates 3 variables as in
* const Apr = 'London'
* const May = 'Paris'
* const June = 'Hong Kong'
*/
const travellingTo = ({ Apr, May, June }) => {
console.log('Apr: ', Apr);
console.log('May: ', May);
console.log('June: ', June);
}
travellingTo(travels);/* On your console, you should see
* Apr: London
* May: Paris
* June: Hong Kong
*/

Remember to make sure you are passing an object when you destructure it in the arrow function. You may want to give the argument a default value to avoid errors:

const travellingTo = ({ Apr, May, June } = {}) => {
console.log('Apr: ', Apr);
console.log('May: ', May);
console.log('June: ', June);
}

5) Spread operator with objects (ES9)

In ES6, you can only use spread operator with arrays or strings, but in ES9, you can use it with objects. It is quite handy for destructuring an object partially while passing the rest as an object without the destructured key-value pairs to functions.

const travels = {
Apr: 'London',
May: 'Paris',
June: 'Hong Kong'
}
const travellingTo = ({ Apr, ...otherMonths }) => {
console.log('Apr: ', Apr);
console.log('otherMonths: ', otherMonths);
}
travellingTo(travels);/* On your console, you should see
* Apr: London
* otherMonths: {
* May: 'Paris',
* June: 'Hong Kong'
* }
*/

6) Object.values() (ES8)

If you have tried to create an array with all the values from an object, then you would know how nice this built-in method is.

const travels = {
Apr: 'London',
May: 'Paris',
June: 'Hong Kong'
}
const valuesOfTravels = Object.values(travels);
console.log(valuesOfTravels);
// on your console, you should see:
// [‘London’, ‘Paris’, ‘Hong Kong’]

7) Object.entries() (ES8)

This is a great method for data processing. It creates an array of all the key/value pairs which have been split into an array tuple.

const travels = {
Apr: 'London',
May: 'Paris',
June: 'Hong Kong'
}
const entriesOfTravels = Object.entries(travels);
console.log(entriesOfTravels);
/* on your console, you should see:
* [
* ['Apr', 'London'],
* ['May', 'Paris'],
* ['June', 'Hong Kong']
* ]
*/

8) Object property shorthand (ES6)

This is for lazy people like me. Remember it is case-sensitive. If you have a variable, it will create a key in the object with the variable name and the value for that key will be the value of the variable.

const apple = 10;
const orange = 2;
const lemon = 8;
const fruits = {
apple,
orange,
lemon

}
// it is same as declaring in this way:
const fruits: {
apple: apple,
orange: orange,
lemon: lemon
}
// or
const fruits: {
'apple': apple,
'orange': orange,
'lemon': lemon
}

9) Object property assignment (ES6)

This is a good and simple method for creating a merged object without mutating the original objects. You set a base object and merge additional object into it sequentially with key/values being replaced if they overlap.

const squirrelBaby = {
fluffy: true,
size: 'small'
}
const squirrelBabyGirl = {
gender: 'female',
age: '0.1'
}
const thisLittleSquirrel = Object.assign({}, squirrelBaby, squirrelBabyGirl);
/* thisLittleSquirrel = {
* fluffy: true,
* size: 'small',
* gender: 'female',
* age: '0.1'
* }
*/

Arrays

10) Rest parameter with arrays (ES6)

Rest parameter with arrays becomes useful when you need to pass in a flexible number of arguments into the function. The rest parameter puts the arguments into one array.

const sumOfAge = (...ageList) => {
let sum = 0;
ageList.forEach(age => sum += age);
return sum;
}
sumOfAge(30, 21, 27, 19, 24);
// output: 121

Async

Two more syntax updates worth mentioning

Other than the syntax above, the native Promise was introduced in ES6 which is extremely handy too. It deserves a long article alone. Since there are already many great articles out there, I would skip it here. If you are interested in knowing more about it, I highly recommend reading this page:

Iterators and generators were also introduced in ES6. However, I don’t find them too useful for day-to-day work. They are mostly used in libraries to deal with async calls, e.g. Redux-Saga. If you are using these libraries, it would be helpful to take a look at iterators and generators, otherwise you probably do not need to learn about them.

I hope this article is clear enough for you to understand what the new syntax are about. Try to implement some of them in your code and see if you like them.

For a full list of ES6 features, please visit https://github.com/lukehoban/es6features#readme
This repo has comprehensive code examples for all the features :)

Follow me if you like this article!
I write about front-end web development and programming whenever I have time.

--

--

Frontend Unicorn. I 💖 CSS & JavaScript. My brain occasionally runs out of memory so I need to pen down my thoughts. ✨💻🦄🌈.y.at