JS Interview #7 — Arrow Function
In this blog, you’ll learn all about JavasScript Arrow Function.
Javascript Traditional Functions
Before looking into the arrow function, we will see JavaScript's normal way of functions. so it will help to show the unique aspects of arrow functions.
As we know JavaScript functions can be loosely classified as the following:
- Function declarations
- Function expressions
Function declaration
function funDeclaration() {
console.log('Javascript function declaration');
};
Function expression
const expression = function() {
console.log('Javascript function expression');
};
Combination of function declaration and expression
const expression = function funDeclaration() {
console.log('combination of function declaration & expression');
};
Arrow Function
The arrow function is one of the features introduced in the ES6 version of JavaScript. It allows you to create functions in a cleaner way compared to regular functions.
const functionA = (parameter1, parameter2, ..., parameterN) => {
// Function Statements
}
The syntax for an arrow function expression does not require the function
keyword and uses a fat arrow (=>
) to separate the parameter(s) from the body.
There are three parts to an Arrow Function or Lambda Function:
- Parameters: Any function may optionally have the parameters.
- Fat arrow notation/lambda notation: It is the notation for the arrow (=>).
- Statements: It represents the function body.
Before Arrow Function
const hello = function() {
return "Hello World!";
}
hello(); // Hello World!
After Arrow Function
const hello = () => {
return "Hello World!";
}
hello(); // Hello World!
Example 1: Arrow Function with No Argument
If a function doesn’t take any argument, then you should use empty parentheses.
const greet = () => {
console.log('Hello')
};
greet(); // Hello
Example 2: Arrow Function with One Argument
If a function has only one argument, you can omit the parentheses.
const greet = x => {
console.log(x)
};
greet('Hello'); // Hello
Example 3: Multiline with Arrow Functions
If a function body has multiple statements, you need to put them inside curly brackets {}
.
let sum = (a, b) => {
let result = a + b;
return result;
}
let result1 = sum(5,7);
console.log(result1); // 12
Example 4: Single-line with Arrow Functions
let sum = (a, b) => a + b;
let result1 = sum(5,7);
console.log(result1); // 12
Example 5: Arrow Function as an Expression
You can also dynamically create a function and use it as an expression.
const age = 5;
const welcome = (age < 18) ?
() => console.log('Baby') :
() => console.log('Adult');
welcome(); // Baby
Example 6: IIFE with Arrow Function
An immediately invoked function expression (IIFE for short) is a JavaScript design pattern that declares an anonymous function and immediately executes it.
(function() {
console.log('Hello, World!');
})();
(() => {
console.log('Hello, World!');
})();
Example 7: Arguments Binding with Arrow Functions
Regular functions have arguments binding. That’s why when you pass arguments to a regular function, you can access them using the arguments
keyword.
const x = function () {
console.log(arguments);
}
x(4,6,7); // Arguments [4, 6, 7]
Arrow functions do not have arguments binding.
When you try to access an argument using the arrow function, it will give an error.
const x = () => {
console.log(arguments);
}
x(4,6,7); // ReferenceError: Can't find variable: arguments
To solve this issue, you can use the spread operator
let x = (...n) => {
console.log(n);
}
x(4,6,7); // [4, 6, 7]
Example 8: Arrow Function with Promises and Callbacks
// ES5
asyncFunction().then(function() {
return asyncFunction1();
}).then(function() {
return asyncFunction2();
}).then(function() {
finish;
});
// ES6
asyncFunction()
.then(() => asyncFunction1())
.then(() => asyncFunction2())
.then(() => finish);
Example 9: new keyword with Arrow Function
// ES5
const x = function() {
console.log("Hello World");
}
const obj = new x(); // Hello World
// ES6
const x = () => {
console.log("Hello World");
}
const obj = new x(); // x is not a constructor
You cannot use an arrow function as a constructor.
Example 10: Arrow function with default parameters
In ES6, the function allows the initialization of parameters with default values.
const show = (a, b=200) => {
console.log(a + " " + b);
}
show(100); // 100 200
Example 11: this with Arrow Function
this
represents an object that executes the current function.
if we understand this through real-life situations like you walking along with your mother and meeting a friend along the way. This is how you would introduce your mom to your friend. This is my mother.
Take a close look at this
is that sentence. this
shows a reference to your mother. this
represents the mother in the current sentence. It is the same way JavaScript uses this
keyword.
The handling this
is also different in arrow functions compared to regular functions.
Let's see how JavaScript will refer to a mother using this
.
const parent = {
mom_name: "Samantha Quinn",
mother: function () {
return `${this.mom_name} is my mother`;
},
};
console.log(parent.mother());
In this example, we used the this
keyword to refer to the parent
. Meaning this
refers to its parent
object. It refers to the context where the anonymous function is called. And this will bind to the parent
object to return the name of the mother.
now let’s check with arrow function with this
.
const parent = {
mom_name: "Samantha Quinn",
mother: () => {
return `${this.mom_name} is my mother.`;
},
};
console.log(parent.mother());
Here we will get undefined with the arrow functions there is no binding of this
.
What if we use this globally? Let’s see that with examples.
function test() {
console.log(this);
}
test();
Run the above call in a browse console. You will get something like:
Window {window: Window, . . . .}
This is because the test()
is called from a global context, and this
will refer to a global object. In this case, a global object window is called from the browser. this
is not defined by the caller.
Key Points to remember
- No more function keywords are need while creating Arrow function
- In Arrow function parenthesis are optional as well as curly braces
- The Arrow function has an implicit return. Thus no curly braces.
- The Arrow function can never be a method.
- The Arrow function can never be a constructor.
- Debugging may not be easy if you create an arrow function without a name (anonymous)
- The Arrow function is a little hard to read.
To understand in a much better way here is the video link