Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • 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
  • Go Premium
  • 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:
Object.create vs. New in JavaScript
Next article icon

JavaScript Object Constructors

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An object is the collection of related data or functionality in the form of key. These functionalities usually consist of several functions and variables. All JavaScript values are objects except primitives. 

const GFG = {
subject : "programming",
language : "JavaScript",
}

Here, subject and language are the keys and programming and JavaScript are the values.

Object Constructor

A constructor function is a special type of function in JavaScript that is used to create and initialize objects. Constructors are used with the new keyword to create instances of a particular type (object). By using constructors, we can easily create multiple instances of the same type of object, all with their own unique properties and methods.

JavaScript
//Driver Code Starts
// Constructor function
//Driver Code Ends

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function() {
        console.log(`My name is ${this.name} and I am ${this.age} years old.`);
    };
}

//Driver Code Starts

//Creating Instances with a Constructor
const p1 = new Person("Akash", 30);
const p2 = new Person("Anvesh", 25);

p1.sayHello();
p2.sayHello();
//Driver Code Ends

Output
My name is Akash and I am 30 years old.
My name is Anvesh and I am 25 years old.

this keyword

The this keyword refers to the object it belongs to, like OOPs languages C++, C#, JAVA etc. this keyword is used in different ways in different areas. While executing a function in JavaScript that has a reference to its current execution context, that is the reference by which the function or data member is called. See the previous example. 

Adding Property to an Object

The property can be added to the object by using dot(.) operator or square bracket.,

const GFG = {
articles: 'computer science',
quantity: 3000,
};

The GFG has two properties "articles" and "quantity". Now we wish to add one more property name called subject.

Using dot (.) operator

GFG.subject: 'JavaScript';

Using square bracket:

GFG['subject']: 'JavaScript';

Here, subject is the property and 'JavaScript' is the value of the property. Adding a property to Constructor: We cannot add a property to an existing constructor like adding a property to an object (see previous point), for adding a property we need to declare under the constructor.

function GFG(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.G = "GEEK";
}

Here, we add a property name G with value "GEEK", in this case the value "GEEK" is not passed as an argument.

Adding a Method to an Object

We can add a new method to an existing object.

GFG.n = function () {
return this.A + this.B;
};

Here, the object is GFG.

Adding a Method to Constructor

function GFG(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.n = function () {
return this.A + this.B;
}
}

Here, in the last line a method is added to an object. 

Instantiating an object constructor

There are two ways to instantiate object constructor,

const object_name = new Object(); // or  
const object_name = new Object("java", "JavaScript", "C#");

const object_name = { };

In 1st method, the object is created by using new keyword like normal OOP languages, and "Java", "JavaScript", "C#" are the arguments, that are passed when the constructor is invoked. In 2nd method, the object is created by using curly braces "{ }".

Assigning properties to the objects: There are two ways to assigning properties to the objects.

  • Using dot (.) operator:
object_name . properties = value;
  • Using third bracket:
object_name [ 'properties'] = value;

Example 1: Object creation by using new keyword and assigning properties to the object using dot(.) operator. 

javascript
let gfg = new Object();

gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";


//Driver Code Starts
console.log("Subject: " + gfg.a);
console.log("Author: " + gfg.b );
//Driver Code Ends

Output
Subject: JavaScript
Author: GeeksforGeeks

Example 2: Object creation using curly braces and assigning properties to the object using third bracket "[]" operator. 

javascript
let gfg = { };

gfg['a'] = "JavaScript";
gfg['b']= "GeeksforGeeks";


//Driver Code Starts
console.log("Subject: " + gfg.a);
console.log("Author: " + gfg.b );
//Driver Code Ends

Output
Subject: JavaScript
Author: GeeksforGeeks

Example 3: This example shows how to use function() with object constructor. 

javascript
let gfg = new Object();

gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";
gfg.c = function () {
    return (gfg.a +" "+ gfg.b);
};


//Driver Code Starts
console.log("Subject: " + gfg.a);
console.log("Author: " + gfg.b);
console.log("Adding the strings: "+ gfg.c() );
//Driver Code Ends

Output
Subject: JavaScript
Author: GeeksforGeeks
Adding the strings: JavaScript GeeksforGeeks

Example 4: Another way to create a function using function name. 

javascript
let gfg = { };

gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";
gfg.c = add;

// Declare function add()
function add() {
    return (gfg.a +" "+ gfg.b);
};


//Driver Code Starts
console.log("Subject: " + gfg.a);
console.log("Author: " + gfg.b);
console.log("Adding the strings: "+ gfg.c());
//Driver Code Ends

Output
Subject: JavaScript
Author: GeeksforGeeks
Adding the strings: JavaScript GeeksforGeeks

Next Article
Object.create vs. New in JavaScript

S

SoumikMondal
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-object
  • javascript-oop

Similar Reads

    What is a Constructor in JavaScript?
    A constructor in JavaScript is a special function that is used to create and initialize objects. When we want to create multiple objects with similar properties and methods, the constructor is used as a blueprint to create similar objects. This is useful when you want to create multiple objects with
    8 min read
    JavaScript Objects
    In our previous article on Introduction to Object Oriented Programming in JavaScript we have seen all the common OOP terminology and got to know how they do or don't exist in JavaScript. In this article, objects are discussed in detail.Creating Objects:In JavaScript, Objects can be created using two
    6 min read
    Default Constructor in JavaScript
    In JavaScript, a default constructor is not explicitly defined like in some other programming languages such as Java or C++. In JavaScript, objects can be created without a formal constructor. When you create an object using the new keyword along with a constructor function, that function serves as
    2 min read
    Object.create vs. New in JavaScript
    The new keyword and Object.create() are frequently used to instantiate objects in JavaScript but they have distinct characteristics and use cases. Understanding the differences between new and Object.create() is essential for mastering object creation in JavaScript. What is new?The new keyword in Ja
    2 min read
    Constructors in Python
    In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
    3 min read
    What is Constructor?
    A constructor is a special type of method used in object-oriented programming languages to initialize objects. The constructor is called automatically every time when an object is created, allowing the object to set initial values for its attributes or perform other setup tasks.In this article, we w
    3 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
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
  • DSA Tutorial
  • 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
  • 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