Arrow vs function
Learn when arrows cannot be used (constructor, arguments).
Arrows cannot be constructors
Arrow functions cannot be used as constructors; calling them with new throws an error. They also have no prototype property.
const Dog = (name) => { this.name = name; };
new Dog("Rex"); // TypeErrorTo create objects, use a classic function or a class. An arrow does not work here, so you must pick another approach.
No arguments object
Arrow functions have no own arguments object. Unlike classic functions, you cannot reach all passed parameters through arguments; it refers to the outer scope's arguments.
const f = () => {
console.log(arguments); // outer arguments
};Instead, use a rest parameter ...args:
const f = (...args) => args;A rest parameter returns a real array; arguments is array-like but not an array.
Exercise Convert the arguments function to an arrow
The sumAll classic function uses arguments. Convert it to an arrow function, use a rest parameter ...numbers, and return the total with reduce.
Show example solution
const sumAll = (...numbers) => numbers.reduce((acc, n) => acc + n, 0);
Test yourself
-
Which throws an error?
- const f = (a, b) => a + b;
- const f = n => n * 2;
- const f = () => 0;
- const f = (n) => { this.n = n; }; new f(5);
Show answer
const f = (n) => { this.n = n; }; new f(5); — Correct. An arrow cannot be called with <code>new</code>; it throws TypeError.
-
Rest instead of arguments
const sum = (____) => args.reduce((a, b) => a + b, 0);Show answer
const sum = (...args) => args.reduce((a, b) => a + b, 0); -
Match the features
- new arrow
- throws TypeError
- arguments in arrow
- outer scope's
- rest parameter
- returns a real array
-
A case where you should NOT use an arrow?
- As a constructor that produces objects
- As an array callback inside map
- As a short single-line helper
- As a setTimeout callback to keep this
Show answer
As a constructor that produces objects — Correct. An arrow cannot be a constructor; <code>new</code> throws.