Posts

Showing posts from May, 2016

Six nifty ES6 tricks

Image
In this blog post, I show six tricks enabled by new ES6 features. At the end of each section, I point to related material in my book “ Exploring ES6 ” (which is free to read online). Enforcing mandatory parameters via parameter default values ES6 parameter default values are only evaluated when they are actually used. That lets you enforce that a given parameter be provided: /** * Called if a parameter is missing and * the default value is evaluated. */ function mandatory() { throw new Error('Missing parameter'); } function foo(mustBeProvided = mandatory()) { return mustBeProvided; } The function call mandatory() is only made if the parameter mustBeProvided is missing. Interaction: > foo() Error: Missing parameter > foo(123) 123 More information: Sect. “ Required parameters ” in “Exploring ES6” Iterating over Array indices and elements via the for-of loop Method forEach() lets you iterate over the elem...

Handling whitespace in ES6 template literals

In this blog post, we look at problems that arise when template literals contain whitespace: Breaking up long lines Dedenting content Joining Arrays Indenting inserted content I’m using the library common-tags by Declan de Wet (with “useful template literal tags for dealing with strings in ES6”) to demonstrate solutions for some of these problems. Breaking up long lines Occasionally, you have long lines that you want to break up. common-tag’s tag function oneLine lets you do that: console.log(oneLine` a single line with many words `); // a single line with many words Dedenting content Template literals let you embed multi-line text content inside JavaScript. The main challenge is that the text must both have proper indentation and fit nicely into its JavaScript surroundings: function foo() { console.log(`<ul> <li>first</li> <li>second</li> </ul>`); } This does not look good...