Return javascript object from function

Ways to Return an Object from an Arrow Function

The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students .

In this post you’ll learn a few different ways to return an object from an arrow function. Sometimes you’ll just want to return an object and not use any local variables inside the function.

Let’s explore some examples that’ll neaten up your codebase and help you understand further workings of the JavaScript language.

The most common and standard way of returning an object from an arrow function would be to use the longform syntax:

const createMilkshake = (name) =>  return  name, price: 499 >; >; const raspberry = createMilkshake('Raspberry'); // 'Raspberry' console.log(raspberry.name); 

This pattern is great, as it allows us to easily add some local variables above the return statement, a common practice for us.

But what if we don’t need to declare any local variables and just want to return an object?

We’ve heard of an arrow function’s implicit return feature — just delete the return statement and the curly <> braces right?

// ❌ Uncaught SyntaxError: Unexpected token ':' const createMilkshake = (name) =>  name, price: 499 >; 

And bam — a syntax error. This is what trips many developers up.

This is because the <> we’re expecting to be the opening/closing object braces have now become the function curlies as soon as we remove the return statement — the JavaScript parser acting as it should.

What’s interesting about JavaScript is its ability to create expressions using parentheses () . By doing exactly this and wrapping our intended object curlies in brackets, we create an expression and therefore return an expression.

This means that essentially the curlies are moved back “inside” the function and form the opening/closing object curlies once more:

// 👍 Perfect const createMilkshake = (name) => ( name, price: 499 >); 

And that’s it. A really nice shorthand for returning objects from an arrow function.

Thankfully this ‘issue’ only applies to returning objects. For all other JavaScript types the implicit return works perfectly without this trick.

Angular Directives In-Depth eBook Cover

Free eBook

Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.

  • Observables and Async Pipe
  • Identity Checking and Performance
  • Web Components syntax
  • and Observable Composition
  • Advanced Rendering Patterns
  • Setters and Getters for Styles and Class Bindings

That went smoothly, check your email.

I hope you enjoyed the post, and if you’d love to learn more please check out my JavaScript courses, where you’ll learn everything you need to know to be extremely good and proficient at the language, DOM and much more advanced practices. Enjoy and thanks for reading!

Learn JavaScript the right way.

The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students .

Источник

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

Источник

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.

Источник

Читайте также:  Css свечение вокруг кнопки
Оцените статью