Code Zen: 8 Time-saving Tips From JavaScript ES6 and Beyond

Sarah Quigley • May 3, 2018

Beautify your code.

JavaScript famously began its life in 1995 as a scripting language prototyped in ten days by Brendan Eich for the browser du jour, Netscape Navigator. Often derided as the bastard child of coding languages, it long lacked many of the features developers took for granted in other languages.

Comparing some popular languages


Comparing some popular languages

In recent years, with the release of JavaScript ES6 (ES2015) and beyond, JavaScript has seen some major transformations, and it can now stand more proudly among other popular programming languages. While most web developers are aware of the bigger additions to the language, such as classesmodules, and arrow functions, some may not be aware of the many smaller syntactic improvements to the language. These features are often not only huge time-savers—they also increase the clarity and conciseness of code. Let’s dive deeper into a few of my favorites.

The little JavaScript that could


The little JavaScript that could

String Interpolation

For years, one of my pet peeves was the lack of string interpolation in JavaScript. As of ES6, template literals add support for string interpolation.

/* ES5 */
var purpose = ‘cat videos’;
var message = ‘The internet is for ‘ + purpose + ‘.’;
/* >= ES6 */
var purpose = ‘cat videos’;
var message = `The internet is for #{purpose}.`;

view rawstring_interpolation.js hosted with ❤ by GitHub

Multiline Strings

Where previously newline characters and concatenation across lines were required, ES6 template literals now provide a simple syntax for multiline strings.

/* ES5 */
var message = ‘The internet is for cat videos.\n’ +
‘A chorus of cats meows from every screen!\n’ +
‘The cuteness is overwhelming.’;
/* >= ES6 */
var message = `The internet is for cat videos.
A chorus of cats meows from every screen!
The cuteness is overwhelming.`;

view rawmultiline_strings.js hosted with ❤ by GitHub

Default Function Parameters

Setting up default parameter values in JavaScript was once painfully verbose. ES6 offers a simple and intuitive syntax for default function parameters.

/* ES5 */
function dogExplainsCats (behaviour, reason) {
if (reason === undefined) {
reason = ‘evil’;
}
return ‘Why cats ‘ + behaviour + ‘? Because cats ‘ + reason + ‘.’;
}
dogExplainsCats(‘poke you in face when sleeping’);
// > ‘Why cats poke you in face when sleeping? Because cats evil.’
/* >= ES6 */
function dogExplainsCats (behaviour, reason = ‘evil’) {
return `Why cats #{behaviour}? Because cats #{reason}!`;
}
dogExplainsCats(‘poke you in face when sleeping’);
// > ‘Why cats poke you in face when sleeping? Because cats evil.’

view rawdefault_function_parameters.js hosted with ❤ by GitHub

Spread Operator

Use of the ES6 spread operator simplifies array concatenation.

/* ES5 */
var cats = [ ‘Maru’, ‘Colonel Meow’, ‘Grumpy Cat’ ];
var moreCats = [ ‘Shironeko’, ‘Zarathustra’].concat(cats);
// > [ ‘Shironeko’, ‘Zarathustra’, ‘Maru’, ‘Colonel Meow’, ‘Grumpy Cat’ ]
/* >= ES6 */
var cats = [ ‘Maru’, ‘Colonel Meow’, ‘Grumpy Cat’ ];
var moreCats = [ ‘Shironeko’, ‘Zarathustra’, …cats ];
// > [ ‘Shironeko’, ‘Zarathustra’, ‘Maru’, ‘Colonel Meow’, ‘Grumpy Cat’ ]

view rawspread_operator.js hosted with ❤ by GitHub

The spread operator can also be used to split strings into an array of individual characters.

/* ES5 */
var lol = «cats»;
var chars = lol.split(«»);
// > [ «c», «a», «t», «s» ]
/* >= ES6 */
var lol = «cats»;
var chars = [ …cats ];
// > [ «c», «a», «t», «s» ]

view rawspread_operator__string_splitting.js hosted with ❤ by GitHub

As of ES2018, you can use the spread operator to copy properties from one object to another.

/* < ES2018 */
var coat = { color: ‘tabby’, mittens: true };
var catMaru = Object.assign({ name: ‘Maru’, likes: ‘boxes’}, coat);
// > { name: ‘Maru’, likes: ‘boxes’, color: ‘tabby’, mittens: true }
/* >= ES2018 */
var coat = { color: ‘tabby’, mittens: true };
var catMaru = { name: ‘Maru’, likes: ‘boxes’, …coat };
// > { name: ‘Maru’, likes: ‘boxes’, color: ‘tabby’, mittens: true }

view rawspread_operator__copying_object_properties.js hosted with ❤ by GitHub

Rest Parameters

The addition of rest parameters (using the spread operator) to ES6 makes the creation of variadic functions (functions accepting a variable number of arguments) elegant and intuitive.

/* ES5 */
function catFight (action) {
var moreActions = Array.prototype.slice.call(arguments, 1);
return action + ‘! ‘ + moreActions.join(‘! ‘) + ‘!’;
}
catFight(‘Slash’, ‘Hiss’, ‘Yowl’);
// > ‘Slash! Hiss! Yowl!’
/* >= ES6 */
function catFight (action, …moreActions) {
return action + ‘! ‘ + moreActions.join(‘! ‘) + ‘!’;
}
catFight(‘Slash’, ‘Hiss’, ‘Yowl’);
// > ‘Slash! Hiss! Yowl!’

view rawrest_parameters.js hosted with ❤ by GitHub

It’s worth noting that you can also use the spread operator to pass arguments to variadic functions such as the above function.

/* ES5 */
var actions = [ ‘Slash’, ‘Hiss’, ‘Yowl’];
catFight.apply(undefined, actions);
// > ‘Slash! Hiss! Yowl!’
/* >= ES6 */
var actions = [ ‘Slash’, ‘Hiss’, ‘Yowl’];
catFight(…actions);
// > ‘Slash! Hiss! Yowl!’

view rawrest_parameters__arguments.js hosted with ❤ by GitHub

Array Destructuring Assignment

Using array destructuring assignment, you can succinctly capture elements of arrays in separate variables.

/* ES5 */
var cats = [ ‘Maru’, ‘Colonel Meow’, ‘Grumpy Cat’ ];
var yayCat = cats[0], lolCat = cats[2];
var tmpCat = yayCat;
yayCat = lolCat;
lolCat = tmpCat;
/* >= ES6 */
var cats = [ ‘Maru’, ‘Colonel Meow’, ‘Grumpy Cat’ ];
var [ yayCat, , lolCat ] = cats;
[ yayCat, lolCat] = [ lolCat, yayCat];

view rawarray_destructuring_assignment.js hosted with ❤ by GitHub

You can even provide default values during destructuring. Neat!

/* ES5 */
var cats = [ ‘Maru’, ‘Colonel Meow’ ];
var yayCat = cats[0];
var lolCat = cats[2] === undefined ? ‘Grumpy Cat’ : cats[2];
/* >= ES6 */
var cats = [ ‘Maru’, ‘Colonel Meow’ ];
var [ yayCat, , lolCat = ‘GrumpyCat’ ] = cats;

view rawarray_destructuring_assignment__defaults.js hosted with ❤ by GitHub

Object Destructuring Assignment

Similar to array destructuring assignment, object destructuring assignment assigns the properties of an object to separate variables in a single statement.

/* ES5 */
var catMaru = { name: ‘Maru’, mittens: true, likes: ‘boxes’ };
var name = catMaru.name;
var mittens = catMaru.mittens;
var likes = catMaru.likes;
/* >= ES6 */
var catMaru = { name: ‘Maru’, mittens: true, likes: ‘boxes’ };
var { name, mittens, likes } = catMaru;

view rawobject_destructuring_assignment.js hosted with ❤ by GitHub

Destructuring can be used on deeply nested objects.

/* ES5 */
var catMaru = {
name: ‘Maru’,
appearance: {
mittens: true,
coat: ‘tabby’
}
};
var name = catMaru.name;
var color = catMaru.appearance.coat;
/* >= ES6 */
var catMaru = {
name: ‘Maru’,
appearance: {
mittens: true,
coat: ‘tabby’
}
};
var { name, appearance: { coat } } = catMaru;

view rawobject_destructuring_assignment__deeply_nested_objects.js hosted with ❤ by GitHub

As with arrays, you may provide default values during object destructuring assignment.

/* ES5 */
var catMaru = { name: ‘Maru’, mittens: true };
var name = catMaru.name;
var mittens = catMaru.mittens;
var likes = catMaru.likes === undefined ? ‘boxes’ : catMaru.likes;
/* >= ES6 */
var catMaru = { name: ‘Maru’, mittens: true };
var { name, mittens, likes = ‘boxes’ } = catMaru;

view rawobject_destructuring_assignment__defaults.js hosted with ❤ by GitHub

As of ES2018, you can use the spread operator when destructuring objects to copy keys not captured separately into an object.

/* < ES2018 */
var catMaru = { name: ‘Maru’, mittens: true, color: ‘tabby’ };
var name = catMaru.name;
var coat = {};
coat.mittens = catMaru.mittens;
coat.color = catMaru.color;
/* >= ES2018 */
var catMaru = { name: ‘Maru’, mittens: true, color: ‘tabby’ };
var { name, …coat } = catMaru;

view rawobject_destructuring_assignment__spread_operator.js hosted with ❤ by GitHub

Yay JavaScript

Of course, before you jump into using these features, there’s always the bugbear of all web development projects to consider: browser support. While modern browsers do support the vast majority of ES6 (ES2015) features (as well as the features of many more recent releases) out of the box, in order to ensure universal support, to support older browsers (notably IE11), and to use the latest features of ES.next, a compiler such as Babel is still necessary. So go set up your favorite compiler and get coding!

Tags: Development, ES6, JavaScript, Productivity, Tips & Tricks

Source:attck.com/blog/time-saving-tips-javascript-and-beyond

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *