|
| 1 | +// @ts-check |
| 2 | + |
| 3 | +//* ****** EcmaScript 2015 (ES6): Default Parameter Values (https://goo.gl/AP5EYb) |
| 4 | +function sum(x = 1, y = 2, z = 3) { |
| 5 | + return x + y + z; |
| 6 | +} |
| 7 | +console.log(sum(4, 2)); // outputs 9 |
| 8 | + |
| 9 | +// function above is the same as |
| 10 | +function sum2(x, y, z) { |
| 11 | + if (x === undefined) x = 1; |
| 12 | + if (y === undefined) y = 2; |
| 13 | + if (z === undefined) z = 3; |
| 14 | + return x + y + z; |
| 15 | +} |
| 16 | +console.log(sum2(4, 2)); // outputs 9 |
| 17 | + |
| 18 | +// or |
| 19 | +function sum3() { |
| 20 | + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; |
| 21 | + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; |
| 22 | + var z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3; |
| 23 | + |
| 24 | + return x + y + z; |
| 25 | +} |
| 26 | +console.log(sum3(4, 2)); // outputs 9 |
| 27 | + |
| 28 | +//* ****** EcmaScript 6: spread operator ('...') (https://goo.gl/8equk5) |
| 29 | +let params = [3, 4, 5]; |
| 30 | +console.log(sum(...params)); // ES2015 |
| 31 | +console.log(sum.apply(undefined, params)); // ES5 |
| 32 | + |
| 33 | +let numbers = [1, 2, ...params]; // pushing values into array |
| 34 | +console.log(numbers); |
| 35 | + |
| 36 | +//* ****** EcmaScript 6: rest parameter ('...') (https://goo.gl/LaJZqU) |
| 37 | +function restParamaterFunction(x, y, ...a) { |
| 38 | + return (x + y) * a.length; |
| 39 | +} |
| 40 | +console.log(restParamaterFunction(1, 2, 'hello', true, 7)); // outputs 9; |
| 41 | + |
| 42 | +// code above is the same as ES5: |
| 43 | +function restParamaterFunction2(x, y) { |
| 44 | + var a = Array.prototype.slice.call(arguments, 2); |
| 45 | + return (x + y) * a.length; |
| 46 | +} |
| 47 | +console.log(restParamaterFunction2(1, 2, 'hello', true, 7)); |
0 commit comments