javascript – Function Default Parameters

Question:

In the ES-2015 standard, it became possible to set default function parameters, it looks like this:

function name(name = 'noname') {
  console.log(name);
}
name()

However, the same effect could be achieved with a hack:

function name(name) {
  var name = name || 'noname'
  console.log(name);
}
name()

In this case, Babel translates such a function like this:

function name() {
  var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'noname';
  console.log(name);
}
name();

Which option is better: as suggested by Babel or using the boolean || ?

Answer:

More correctly as babel, of course. Because for example:

> "" || "default"
-> "default"

and if you want to pass an empty string to your function, then its behavior will be slightly unexpected.

Scroll to Top