Notes

[ES2015] Default values

Edit on GitHub

JavaScript
2 minutes

Default Values

Here’s how we used to do default parameter values before.. Say we have a function that returns 42 is no parameter value is provided and if a value is passed, it returns the value.

1function foo (x) {
2  x = x || 42 // Using the OR operand `||` to give 42 if x is false
3  return x
4}
5
6foo(3) // 3
7foo(99) // 99
8
9foo(0) // 42  eh?

0 equals falsy. So even if you did pass a value for x, it returned the default 42. Here’s a better way to rewrite the function above

1function bar (x) {
2  x = x !== undefined ? x : 42 // If x is provided, use x. If x is not provided (undefined), use 42
3  return x
4}
5
6bar(99) // 99
7bar(0) // 0
8bar() // 42
9bar(undefined) // 42

This is the imperative form, we are telling JS how to compute the default value

And here’s the ES6 way of doing it, using default variables

1function baz (x = 42) {
2  return x
3}
4
5baz(99) // 99
6baz(0) // 0
7baz() // 42
8baz(undefined) // 42

Lazy Expressions

A lazy expression is an expression that is not evaluated untill or unless it’s needed.

holding on to an expression and only evaluating it when you need it. It pairs neatly with memoization - keeping the results of evaluated expressions in memory so that you don’t have to evaluate them every time you need their result.

Default values can be ay kind of valid expression.

 1function bar () {
 2  console.log('!')
 3}
 4
 5function foo(x = bar()) {
 6
 7}
 8
 9foo(1) // undefined, bar() not called
10foo() // "!", bar() called once
11foo() // "!", bar() called twice

bar() above will not be called as long as it’s not needed.

Here are two other examples, you can pass functions as default parameter values

 1function required () {
 2  throw 'Parameter required'
 3}
 4
 5function foo(id = required()) {
 6  return id
 7}
 8
 9foo(872) // 872
10foo('aamnah') // "aamnah"
11foo() // Uncaught Parameter required
1var x = 1
2
3function foo(x = 2, f = function() { return x }) {
4  console.log( f() )
5}
6
7foo() // 2

Related