Introduction
In previous practice (ES5) the following approach was used to define the default values of funkcje parameters:
|
1 2 3 4 5 |
function saberi (x, y) { x = x || 10; y = y || 100; console.log(x+y); } |
The problem occurs when a value is passed that the compiler implicitly converts to a boolean “false” (eg zero), and therefore takes the default value instead:
|
1 |
saberi(0, 50) // Returns: 60 |
So we need to improve the condition:
|
1 |
x = (x !== undefined) ? x : 11; |
ES2015 syntax
With the new standard came a simpler syntax for defining default values with the following rule:
The default defined value is applied in case the argument is missing or undefined and “null” is a valid value!
|
1 2 3 4 5 6 7 8 9 |
function test(x = 1) { console.log(typeof num); } test(); // 'number' (x is defined as: 1) test(undefined); // 'number' (x is defined as: 1 too) test(''); // 'string' (x is defined as: '') test(null); // 'object' (x is defined as: null) |

Defining a parameter default value also works well in conjunction with destructuring:
|
1 2 3 4 5 |
function test([x, y] = [1, 2], {z: z} = {z: 3}) { return x + y + z; } test(); // Returns: 6 |
Besides the aforementioned missing value or “undefined”, the default value can be anything else, and even another function:
|
1 2 3 4 5 6 7 8 9 10 |
function multiply (a) { return a * 2; } // Default parameters are also available to later default parameters function foo (num = 1, duplo = multiply(num)) { return [num, duplo]; } console.log(foo()); // Returns: [1, 2] console.log(foo(6)); // Returns: [6, 12] |

