Arrow Functions, Defaults and Rest

Short arrow functions, a default parameter for when an argument is missing, and ...rest to accept any number of arguments.

JavaScript · beginner · 6 min · 14 steps · free

What you'll learn

ArrowFunctions.js

const double = (x) => x * 2;
const greet = (name = 'friend') => `Hello, ${name}!`;
const sum = (...numbers) => numbers.reduce((total, n) => total + n, 0);

console.log(double(21));
console.log(greet());
console.log(greet('Ada'));
console.log(sum(1, 2, 3));

Step by step

  1. An arrow function stored in double. With no braces, the expression after => is returned.
  2. greet is created with the value (name = 'friend') => Hello, ${name}!.
  3. sum is created with the value (...numbers) => numbers.reduce((total, ….
  4. double gets x = 21 and returns 42.
  5. double() has finished, so its variables are gone. It prints 42.
  6. greet() was called with no argument, so name takes its default, "friend".
  7. greet() has finished, so its variables are gone. It prints Hello, friend!.
  8. greet gets name = "Ada" and returns "Hello, Ada!".
  9. greet() has finished, so its variables are gone. It prints Hello, Ada!.
  10. reduce calls the arrow for each number: total = 0 + 1.
  11. reduce callback gets total = 1, n = 2 and returns 3.
  12. reduce callback gets total = 3, n = 3 and returns 6.
  13. ...numbers gathered all three arguments into one array, and reduce added them up: 6.
  14. sum() has finished, so its variables are gone. It prints 6.

Common mistakes

Best practices

Key takeaways

Check yourself

(a, b) => { a + b } returns?

Answer: undefined. With braces you need return.

f(...n) with f(1, 2): n is?

Answer: [1, 2]

·

More in Functions