Understanding Default Parameters in JavaScript

In ECMAScript 2015, default function parameters were introduced to the JavaScript language. These allow developers to initialize a function with default values if the arguments are not supplied to the function call. Initializing function parameters in this way will make your functions easier to read and less error-prone, and will provide default behavior for your functions. This will help you avoid errors that stem from passing in undefined arguments and destructuring objects that don’t exist.

In this article, you will review the difference between parameters and arguments, learn how to use default parameters in functions, see alternate ways to support default parameters, and learn what types of values and expressions can be used as default parameters. You will also run through examples that demonstrate how default parameters work in JavaScript.

Something that’s not really underlined in the article is the fact that these default function parameters are evaluated at call time. Take this snippet for example:

function test(when = new Date()) {
  console.log(when);
}

In case when is omitted (and thus has the value of undefined), its value will be set to the date it was at the moment the function was called.

💡 This way you can also build required parameters into JavaScript:

Understanding Default Parameters in JavaScript →

🧞‍♂️ The way default function parameters in JavaScript work is something that’s actually on my PHP wishlist: at call time evaluation of a default argument value. That way we could default a function argument $when to be new \DateTime('now', new \DateTimeZone('UTC')) in case it’s omitted.

// As you have to do it now
function isCardValidAtTime(Card $card, \DateTime $when = null) {
  $when = $when ?? new \DateTime('now', new \DateTimeZone('UTC'));
  // (function logic)
}

// As I would like to do it in
function isCardValidAtTime(Card $card, \DateTime $when = new \DateTime('now', new \DateTimeZone('UTC'))) {
  // (function logic)
}

Shipping ES6 ES2015 Modules to Browsers

UPDATE 2017.09.13: Deploying ES2015+ Code in Production Today also provides a good writeup on this subject.

Good workflow fleshed out by Sam Thorogood on using ES2015/ES6 modules with browsers that support, whilst also keeping older browsers (that don’t support it) happy.

The modules

Let’s take these 2 simple modules for example:

// main.js
import {x} from ./foo.js
x().then(y => log(y));
// foo.js
export async function x() {
  let y = await fetch('...');
  y = await y.json();
  return y;
}

Shipping your code to browsers that do support ES6 Modules

  1. Include your main.js script as a module
    <script type="module" src="main.js"></script>
  2. There is no step 2

Shipping your code to browsers that don’t support ES6 Modules (and thus don’t support ES6)

  1. Use tools – like Rollup – to combine all your ES6 modules into one single file
  2. Transpile the generated module from ES6 to ES5
  3. Include the transpiled script as you’d normally do, but with a nomodule attribute so that the browsers that do support ES6 modules don’t load it (*)
    <script nomodule src="compiled.js"></script>

As both methods exclude each other, use ‘m both and you’re good to go 🙂

(*) As also detailed in Jake Archibald’s great introduction to ECMAScript modules (which you should read) there’s one nasty issue though: Safari 10.1 & Mobile Safari 10.3 don’t support the nomodule attribute. Luckily there’s a workaround to fixing this.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Introduction to commonly used ES6 ES2015 features

Good overview to get started with ES2015 by Zell Liew in case you’re still not using it (which you should; just do it!). As he puts it:

JavaScript has progressed a ton in the recent years. If you’re learning JavaScript in 2017 and you haven’t touched ES6 ES2015, you’re missing out on an easier way to read and write JavaScript.

Introduction to commonly used ES6 ES2015 features →

ES6 ES2015: Easily remove duplicates from an Array

Say you have a JavaScript Array containing duplicate values. By creating a Set – which only stores unique values (primitive values or object references) – and then spreading that Set into a new Array you can easily dedupe the given Array:

// Array with duplicates
const arr = [7, 3, 1, 3, 3, 7];

// Dedupe using a Set, which is then spread into a new Array
const deduped = [...new Set(arr)];

// -> [ 7, 3, 1 ]

I really dig the spread operator. There’s some more interesting stuff you can do with it.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Sublime HyperClick

51558bb4-971c-11e6-8ef2-d256da53d1da

Most of the time when you are navigating and reading a code-base, you need to jump between required/imported (whatever jargon your programming language uses) files. The “Go to Definition” functionality of Sublime falls short for most languages since jumping between these required files needs some knowledge about how the language or package manager of the language is working.

HyperClick tries to solve this issue. Currently, it knows how to jump between files in Javascript and Sass but can be easily extended to support more languages.

Ooh, I like this plugin a lot. Especially when clicking through our React+Redux based projects at work which tend to have a lot of files requiring each other.

UPDATE 2016.11.29: I’ve added support for Stylus to HyperClick. The pull request has already been merged 🙂

Sublime HyperClick →

ES6 ES2015: Looping over an Object with keys and values

javascript-logo-banner

Say you have an object like this:

const obj = {
    firstName: 'John',
    lastName: 'Doe',
    age: 50,
    eyeColor: 'blue'
};

Using lodash’s forEach you can easily loop over this object, with easy access to both the key and the value:

_.forEach(obj, function(value, key) {
    console.log(key + ' ' + value);
});

But what about ES2015? After fiddling a bit, I came to the conclusion that a simple one-liner is all it takes to loop over it:

for (const [key, value] of Object.entries(obj)) {
    console.log(`${key}: ${value}`);
}

The output will be this:

firstName: John
lastName: Doe
age: 50
eyeColor: blue

In case you were wondering, here’s how it works:

  1. Object.entries() returns an array (with numeric indices) of key-value pairs.
    object-entries
  2. Using for ... of we loop all those pairs.
  3. Thanks Array Destructuring we can assign easily assign both the key and value into the key and value variables.

Alternatively you can also get the same result using Array#forEach(), which might be more readable to you (and has a closer resemblance to _.forEach):

Object.entries(obj).forEach((entry) => {
    const [key, value] = entry;
    console.log(`${key}: ${value}`);
});

You can make this even more condense by destructuring directly in the function:

Object.entries(obj).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

💻 The examples embedded in this post are part of a talk on ESNext named “What’s next
 for JavaScript?”, which I gave at a Fronteers België meetup and Frontend United 2018 (Utrecht). You can check the slides / a recording out here. I’m available for bringing this talk at your meetup/conference.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Check if a browser supports ES6 ES2015

javascript-logo-banner

Great snippet by Benjamin De Cock:

var supportsES6 = function() {
  try {
    new Function("(a = 0) => a");
    return true;
  }
  catch (err) {
    return false;
  }
}();

The critical test is the a = 0. All browsers supporting default parameters have a fairly complete support of ES6 — for example, Edge 13 will be rejected by this test despite a decent ES6 coverage.

The Stripe website for example ships with untranspiled ES6, which is only executed if the supportsES6 check checks out:

if (supportsES6) {
  var script = document.createElement("script");
  script.src = "my-es6-file.js";
  document.head.appendChild(script);
}

Test if ES6 ES2015 is ~fully supported →

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

ES6 ES2015 and React snippets for Sublime Text

gif

babel-sublime-snippets contains a set of shorthands for Sublime Text to working more easily with ES2015 and React.

With it, for example, you can just type cdup followed by a TAB and you’ll end up with componentDidUpdate(prevProps, prevState) {…}.

Find it as Babel Snippets through Package Control.

babel-sublime-snippets

From Coffeescript to ES6 ES2015

decaffeinate

At work we used write most of JavaScript in Coffeescript. Used to. In our most recent projects we now write ES6 (in combination with Babel).

In the transition from Coffeescript to ES6, I found these resources helpful: