Learn Functions in JavaScript | Day 34 | Arrow And Return Keyword | Web development course 2023

1 year ago
11

rrow functions are a concise way to write JavaScript functions. They were introduced in ES6 and offer several advantages over traditional function declarations, including:

Conciseness: They are written using shorter syntax.
Lexical this binding: They capture the this value of the enclosing scope.
Implicit return: They can implicitly return the value of the expression in their body.
Here's the basic syntax of an arrow function:

JavaScript
(parameters) => expression
Use code with caution. Learn more
The parameters and the expression are separated by an arrow (=>). If the function has no parameters, you can use empty parentheses.

Return Keyword:

The return keyword is used to explicitly return a value from a function. However, in arrow functions with a single expression in their body, the return keyword is implicit. This means you don't need to write it explicitly, and the expression's value will be the function's return value.

Here are some examples:

1. Single expression:

JavaScript
const double = (number) => number * 2;

const result = double(5); // result will be 10
Use code with caution. Learn more
2. Multiple expressions:

JavaScript
const isEven = (number) => {
if (number % 2 === 0) {
return true;
} else {
return false;
}
};

const number = 8;
const isEvenResult = isEven(number); // isEvenResult will be true
Use code with caution. Learn more
3. Implicit return:

JavaScript
const square = number => number ** 2;

const area = square(10); // area will be 100
Use code with caution. Learn more
Key Points:

Arrow functions are concise and have lexical this binding.
In arrow functions with a single expression, the return keyword is implicit.
You can still use the return keyword explicitly in arrow functions with multiple expressions.

Loading comments...