JavaScript: Return Object Literal From Arrow Function

Author - Webner
31.03.2020
|
0 Comments
||

javascript arrow function

Arrow function

Arrow function was introduced in ES6, which provides a better and shorter way to write functions in JavaScript. Its another advantage is that it does not bind its own “this”. We can also say that the context inside arrow functions is lexically or statically set.
Syntax:
functionName = () => { body }

Problem

Problem while returning object literal is that when we define it in the following way, it returns “undefined” instead of the object.
Syntax:
returnObject = () => {
Name:”demo”
}

Solution

The main reason for this issue is that parser interprets the opening parenthesis as a block instead of an expression. To solve this issue we can use the following way to define the function which returns the object literal.
Syntax:
returnObject = () => ({
Name:”demo”
})

The parentheses force the parser to treat the object literal as an expression instead of a block statement. When the parser detects parentheses around the entire object literal (an expression), it is not treated as a block statement.
According to the ECMA Script specification, block statements cannot be parenthesized, so the opening parenthesis will be considered as an expression.

What is an Arrow function?

Arrow function was introduced in ES6 to provide a better and shorter way to write functions in JavaScript.

What is another advantage of Arrow function?

Its another advantage is that it does not bind its own “this”. We can also say that the context inside the arrow function is lexically or statically set.

What is the problem while returning object literal?

Problem while returning object literal is that when we define it in the following way, it returns “undefined” instead of the object.

How can we solve the object literal returning problem?

The main reason for this issue is that parser interprets the opening parenthesis as a block instead of an expression. To solve this issue we can use the following way to define the function which returns the object literal.
Syntax:
returnObject = () => ({
Name:”demo”
})

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *