JavaScript is an object-based programming language where functions, arrays, and methods are the most important and core object. Working in this programming language, you get familiar with the functions and the return types. If you define a function, it becomes necessary to return the value of the created object. To do so, the “return” statement is utilized for this purpose. Furthermore, you can also return the function value in the form of a string with the help of a “return” statement along with “this” keyword.
This post will demonstrate how a function returns an object in JavaScript.
How a Function Returns an Object in JavaScript?
To return a defined object from a JavaScript function, the “return” statement can be used. Furthermore, a function can also return an object by using the “return” statement with the “this” keyword to return the object in the string form. For detail, check out the stated examples discussed below.
Example 1: Function Returning an Object in String Form Using “return” Statement With “this” Keyword
In this stated example, the function returns an object in a string form by using the return statement with the “this” keyword. To do so, follow the below code:
- First, initialize an object and assign the value to it.
- Invoke a “function()” and use the “return” statement along with “this” keyword to access the key value:
name : "Jack",
category : "JavaScript",
age : 25,
details : function() {
return this.name + " is working on " + this.category;
}
};
Then, call the function as the argument of the log() method to display the result on the console:
As a result, the function returns the object in the form of string:
Example 2: Function Return an Object in List Form Using Dot Notation
You can use the dot notation to return an object in JavaScript from a function. For that purpose, check out the below code:
- First, declare the function with a particular name and pass the parameters to the functions according to your requirements.
- Then, utilize the “return” statement and pass the declared key to return the value of that key:
var fname = fn;
var lname = ln;
var category = c;
return {
_fname: fname,
_lname: lname,
_category: category
}
};
Next, invoke the defined function and pass the values as its parameter. Then, store these values in an object:
Invoke the “log()” method and pass the object along with the key with the help of dot notation to show output on the screen:
console.log("Last Name:" + obj._lname);
console.log("Category:" + obj._category);
Output
That’s all about the function returning an object in JavaScript.
Conclusion
The function returns an object in JavaScript with multiple methods. To do so, the “return” statement can be used. Furthermore, a function can also return an object by using the “return” statement along with the “this” keyword to concatenate the object in the string form and then return. This tutorial has demonstrated a function returning an object in JavaScript.