Arrow Functions
JavaScript Fundamentals: Arrow Functions
What is the definition of an arrow function?
View Answer:
Interview Response: An arrow function expression is a compact alternative to a traditional function expression, but it is limited, and we should not use it in all situations.
Code Example:
// Arrow Function
let sayHello = (name) => 'Hello, ' + name;
console.log(sayHello('JavaScript!'));
// Function Expression
let sayHello = function (name) {
return 'Hello, ' + name;
};
console.log(sayHello('JavaScript!'));
What are the differences and limitations between Arrow Functions and Function Expressions?
View Answer:
Interview Response: An arrow function does not have bindings to this or super, and we should not use it as a method or constructor. Also, it is not suitable for the call, apply, and bind methods.
Technical Response:
Differences & Limitations:
Differences & Limitations:
- It does not have its binding to this or super and should not get used as a method.
- It does not have arguments or new.target keywords.
- Not suitable for the call, apply and bind methods, which generally rely on establishing a scope.
- It cannot get used as a constructor.
- It cannot use yield within its body.
Code Example:
'use strict';
var obj = {
// does not create a new scope
i: 10,
b: () => console.log(this.i, this),
c: function () {
console.log(this.i, this);
},
};
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}
If there are no arguments in an arrow function, do you need to add the parentheses?
View Answer:
Interview Response: Yes, if there are no arguments, then the parentheses should be present in your arrow function. Otherwise, it throws a syntax error.
Code Example:
// Arrow Function with no argument
let sayHi = () => alert('Hello!');
sayHi(); // returns Hello!
Can you dynamically create a function with an arrow function?
View Answer:
Interview Response: Yes, it is possible to create an arrow function in JavaScript dynamically. An example is a ternary statement that returns two anonymous arrow functions.
Code Example:
let age = prompt('What is your age?', 18);
let welcome = age < 18 ? () => alert('Hello') : () => alert('Greetings!');
welcome();
What is the difference between a single and multiline statement in an arrow function?
View Answer:
Interview Response: A multiline statement must get enclosed in curly brackets, but we can omit the curly brackets in a single-line statement.
Code Example:
let sum = (a, b) => {
// the curly brace opens a multiline function
let result = a + b;
return result; // if we use curly braces, then we need an explicit "return”.
};
alert(sum(1, 2)); //
// Single Line
let sum = (a, b) => a + b;
console.log(sum(3, 6)); // returns 9