Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to print the content of an object in JavaScript ?
Next article icon

How a Function Returns an Object in JavaScript ?

Last Updated : 06 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript Functions are versatile constructs that can return various values, including objects. Returning objects from functions is a common practice, especially when you want to encapsulate data and behavior into a single entity. In this article, we will see how a function returns an object in JavaScript.

Why return objects from Function?

  • Encapsulation: Functions bundle related data and behavior, making code more organized.
  • Reusability: Objects returned by functions can be used across the application.
  • Data Hiding: You can control access to data within an object.

How a Function Returns an Object?

When a function returns an object in JavaScript, it follows a specific sequence of steps. Let's break down the working of a function returning an object

Function Definition

The process starts with defining a JavaScript function. This function will be responsible for creating and returning an object. The function can have parameters that allow you to customize the properties and values of the object it will return. Here's an example of a function declaration:

function createPerson(name, age) {
// Function logic goes here
}

Object Creation

Within the function, you create a new object. You can initialize this object in various ways, either by using object literal notation or by calling a constructor function. The object will typically have properties and values, which can be set based on input parameters or any other logic you need:

function createPerson(name, age) {
let person = {
name: name,
age: age,
};
}

In this example, we create an object "person" with "name" and "age" properties based on the "name" and "age" parameters passed to the function.

Return Statement

To return the newly created object from the function, you use the return statement. The return statement specifies the value (in this case, the object) that the function will provide as its result when called:

function createPerson(name, age) {
let person = {
name: name,
age: age,
};
return person;
}

Function Invocation

To obtain the object returned by the function, you call the function and assign the returned value to a variable:

let john = createPerson("John", 30);

In this line of code, we call the "createPerson" function with arguments "John" and "30", and the returned object is assigned to the variable "john".

Using the Object

Now, you can work with the john object just like any other JavaScript object. You can access its properties, modify them, or use the object in your code as needed:

console.log(john.name); // Output: "John"
console.log(john.age); // Output: 30

Complete Implementation

Example: This example implements the above steps combined in sequence.

JavaScript
function createPerson(name, age) {     let person = {         name: name,         age: age,     };     return person; } let john = createPerson("John", 30); console.log(john.name); // Output: "John" console.log(john.age); // Output: 30 

Output
John  30  

Next Article
How to print the content of an object in JavaScript ?
author
ayushi_awasthi_
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-functions
  • javascript-object
  • Geeks Premier League 2023

Similar Reads

  • How to Store an Object sent by a Function in JavaScript ?
    When a function in JavaScript returns an object, there are several ways to store this returned object for later use. These objects can be stored in variables, array elements, or properties of other objects. Essentially, any data structure capable of holding values can store the returned object. Tabl
    2 min read
  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 min read
  • Are functions objects in javascript?
    Yes, Functions are considered first-class objects, which means they have the same capabilities as other objects. The following are examples that demonstrates functions behaving as objects: Can be assigned to variable [GFGTABS] JavaScript // Assign a function to a variable const x = function() { retu
    1 min read
  • How to print the content of an object in JavaScript ?
    To print the content of an object in JavaScript we will use JavaScript methods like stringify, object.values and loops to display the required data. Let's first create a JavaScript Object containing some key-values as given below: C/C++ Code // Given Object const obj = { name: 'John', age: 30, city:
    3 min read
  • How to transform String into a function in JavaScript ?
    In this article, we will see how to transform a String into a function in JavaScript. There are two ways to transform a String into a function in JavaScript. The first and easy one is eval() but it is not a secure method as it can run inside your application without permission hence more prone to th
    3 min read
  • How to pass primitive/object types through functions in JavaScript ?
    In this article, we learn how JavaScript primitive/object types passed through functions. First, we will see, what are primitive and object data types in JavaScript: 1. Primitive data type: The predefined data types that are provided by JavaScript are called primitive data type. The primitive data t
    4 min read
  • How to Pass Object as Parameter in JavaScript ?
    We'll see how to Pass an object as a Parameter in JavaScript. We can pass objects as parameters to functions just like we do with any other data type. passing objects as parameters to functions allows us to manipulate their properties within the function. These are the following approaches: Table of
    3 min read
  • How to create object properties in JavaScript ?
    JavaScript is built on an object-oriented framework. An object is a collection of properties, where each property links a key to a value. These properties are not in any specific order. The value of a JavaScript property can be a method (function). Object properties can be updated, modified, added,
    4 min read
  • All about Functions and Scopes in JavaScript
    In this article, we will cover all the basic concepts of JS functions, callbacks, scopes, closures in-depth which would help you to - understand different types of function declarations.make better use of functions.understand how different scopes and scope chain works in JS.learn about closures and
    10 min read
  • How to access object properties from result returned by async() function in JavaScript ?
    In this article, we will see how to access the properties of a javascript object result returned by the async() function in Javascript. A javascript object property is a variable that is associated (read attached) with the object itself, i.e. the properties have a name and value is one of the attrib
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences