Javascript functions return object

Return an Object From a Function in JavaScript

Return an Object From a Function in JavaScript

  1. Return an Object From a Regular Function in JavaScript
  2. Return an Object From an Anonymous Function in JavaScript
  3. Return an Object From an Arrow Function in JavaScript

Whenever we say we want to return an object from a function, we return one object from another object (function). There are various ways to return an object using a function.

Let us now see how we can return an object from a function in JavaScript.

Return an Object From a Regular Function in JavaScript

There are various types of functions in JavaScript. Each of these functions is defined differently.

We will see each of these function types, and we will also see if we have to return an object using each of these functions in JavaScript and to return anything from a function, we always use a keyword known as return .

The regular function is a traditional way of defining a function in JavaScript. This type of function is present in the JavaScript programming language from its initial versions.

This function has three things, a function keyword, function name, and function body.

We have created a function called returnObj to return an object. This function aims to return an object.

We have created an obj object with two fields: the name and the company inside this function.

function returnObj()   var obj =   "name": "Adam",  "company": "Google",  >  return obj; >  var myObj = returnObj(); console.log(myObj); 

We must use a return keyword to return this object and return the obj created.

We must create a variable myObj and then call the returnObj function. After we call this function, whatever the function will return (in this case, an object) will be stored inside the myObj variable.

Finally, if you print the variable myObj , you will get the entire object as the output.

Return an Object From an Anonymous Function in JavaScript

An anonymous function is a function that does not have a name associated with it. This type of function only has a function keyword and a function body.

It was introduced in the ES6 version of JavaScript. Since this function does not have a name, we can’t call this function.

So, to call this function, we store this entire function into a variable first, and then we use this variable name as a function name to call this function, i.e., we add round brackets at the end.

Here, we have created a function that does not have a name. And we have created the same object obj which we have created earlier.

const myObj = function ()  var obj =   "name": "Adam",  "company": "Google",  >  return obj; >  console.log(myObj()); 

Finally, we will return this obj , and then after we call this function, the object we are returning from the function will be stored inside that variable.

Return an Object From an Arrow Function in JavaScript

The arrow function is also known as an anonymous function. The only difference between an arrow function and an anonymous function is that the arrow function does not use the function keyword while declaring a function.

Instead, it uses arrows (combination of equals and greater than sign) => to declare a function. This type of function was also introduced in the ES6 version of JavaScript.

Here, we have created an empty object, obj . We will create an arrow function that takes an object as a parameter ( entireObj ).

Inside the arrow function’s body, we will set the name and company properties of the entireObj object with some values. Then we will return the entireObj using the return keyword.

var obj = <>; const myObj = (entireObj)=>  entireObj.name = "Adam";  entireObj.company = "Google";  return entireObj; >  console.log(myObj(obj)); 

In the end, we will call the function myObj . Don’t forget to pass the empty object we created at the start as the parameter while calling the myObj function.

The result of this operation, i.e., the object, will be stored inside the myObj variable and then printed on the console.

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

Related Article — JavaScript Function

Источник

How a Function Returns an Object in JavaScript

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:

var emp = {
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:

function emp ( fn, ln , c ) {
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 ( «First Name:» + obj._fname ) ;
console.log ( «Last Name:» + obj._lname ) ;
console.log ( «Category:» + obj._category ) ;

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.

Источник

How to return an object from a JavaScript function?

To return an object from a JavaScript function, use the return statement, with this keyword.

Example

You can try to run the following code to return an object from a JavaScipt function −

     

Output

Abhinaya

  • Related Articles
  • How to return an object from a function in Python?
  • How to return a json object from a Python function?
  • How to return a value from a JavaScript function?
  • How to return a string from a JavaScript function?
  • How to return a matplotlib.figure.Figure object from Pandas plot function?
  • How to return a JSON object from a Python function in Tkinter?
  • How to return an array from a function in C++?
  • How to return object from an array with highest key values along with name — JavaScript?
  • How to pass an object as a parameter in JavaScript function?
  • How can we use a JavaScript function as an object?
  • How to call a JavaScript function from an onClick event?
  • How to call a JavaScript function from an onsubmit event?
  • How to call a JavaScript function from an onmouseover event?
  • How to call a JavaScript function from an onmouseout event?
  • How to return an object by parsing http cookie header in JavaScript?

Annual Membership

Enjoy unlimited access on 5500+ Hand Picked Quality Video Courses

Training for a Team

Affordable solution to train a team and make them project ready.

Tutorials PointTutorials Point

  • About us
  • Refund Policy
  • Terms of use
  • Privacy Policy
  • FAQ’s
  • Contact

Copyright © Tutorials Point (India) Private Limited. All Rights Reserved.

We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy. Agree Learn more

Источник

Returning Object Literals from Arrow Functions in JavaScript

Arrow functions are one of the great new features of ECMAScript 2015. They allow you to define functions using a concise syntax that doesn’t require the function keyword.

Using the classical function expression syntax, you could define a function to square a given integer as follows:

var square = function (n)  return n * n; >;

Using arrow function notation, on the other hand, it looks a little differently:

let square = n =>  return n * n; >;

Note that the arrow function expression easily fits in one line and is still readable. The body of the function contains a single return statement which returns a binary expression. Because we have a single return statement within the body, we can shorten the function expression even further and omit both the wrapping block statement and the return keyword:

This way, the body of the function is a simple binary expression and the code is a lot shorter than before. Let’s now try to return an object literal from a function instead of a primitive value.

#Returning Object Literals from Arrow Functions

Let’s assume we want the square function to return the square of the given number as a property of an object literal. This is how we’d traditionally define the function:

var square = function (n)  return  square: n * n, >; >;

If you were to rewrite this function expression as an arrow function, you might be tempted to simply translate it just like we did in the previous example, like this:

let square = n =>  square: n * n; >;

When you call square , though, you’ll notice the function doesn’t work as intended. No matter which input value you pass, you’ll get undefined as a return value. Why is that?

The issue with the arrow function is that the parser doesn’t interpret the two braces as an object literal, but as a block statement. Within that block statement, the parser sees a label called square which belongs to the expression statement n * n . Since there’s no return statement at all, the returned value is always undefined .

To be precise, the body of the function consists of a block statement whose statement list contains a single statement, a labeled statement. Its body is an expression statement holding the binary expression. There’s no return statement.

What you need to do is force the parser to treat the object literal as an expression so that it’s not treated as a block statement. The trick is to add parentheses around the entire body:

let square = n => (< square: n * n >);

Once the parser encounters the opening parenthesis, it knows from the ECMAScript grammar that an expression must follow because block statements can’t be parenthesized. Therefore, it parses an object literal (which is an expression) rather than a block statement (which is not).

And there you go! Parentheses do the trick.

JavaScript Promises in Depth

JavaScript Promises in Depth

ES2015 brought a native Promise implementation to the JavaScript standard library. In this course, we’re going to take an in-depth look at how to use promises to model asynchronous operations in JavaScript.

Источник

Читайте также:  Call public class in java
Оцените статью