Which arrow function returns x * 2?
Only an expression body (no braces) returns implicitly. With braces the body is a block and needs an explicit return x * 2.
Arrow Functions · Exercise 1 of 4
Fifteen multiple-choice questions on JavaScript arrow functions: syntax and implicit return, returning objects, lexical this, arrows as methods, arguments, new and prototype, call/apply/bind, hoisting, class fields and syntax rules. Pick an option to check your answer instantly.
Which arrow function returns x * 2?
Only an expression body (no braces) returns implicitly. With braces the body is a block and needs an explicit return x * 2.
Which arrow function returns the object { ok: true }?
The parentheses tell the parser the braces are an object literal. () => { ok: true } is a block with a label and returns undefined.
Where does an arrow function get its this from?
Arrows have no this binding; this is resolved lexically, like any outer variable. Regular functions get this from the call.
How should an arrow function access all the arguments it was called with?
Arrows have no own arguments object; the name would refer to an enclosing regular function's arguments. Rest parameters give a real array.
What happens with const Person = (name) => { this.name = name; }; new Person("Asha");?
Arrow functions have no [[Construct]] behaviour or prototype, so new rejects them. Use a class or a regular function.
Why does const user = { name: "Asha", hi: () => this.name }; not return "Asha" from user.hi()?
Calling user.hi() does not give an arrow a this. Write hi() { return this.name; }.
What does arrowFn.call(obj, 1, 2) do?
call/apply/bind still pass arguments to arrows, but their this argument has no effect.
What happens when greet() is called on the line before const greet = () => "hi";?
An arrow is an expression; only the variable is hoisted. With var the call would be a TypeError (greet is undefined).
Where is an arrow function the best choice?
Arrows shine as callbacks that should keep the surrounding this. Prototype methods and constructors need a dynamic this; generators need function*.
Why is Car.prototype.start = () => this.engine.on(); a bug?
Methods shared through a prototype rely on this being the object they were called on, which only regular functions (or method syntax) provide.
Timed online tests with instant scores and explanations.