The Wayback Machine - https://web.archive.org/web/20240527193804/https://www.geeksforgeeks.org/objects-in-javascript/
Open In App

Objects in Javascript

Last Updated : 27 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Objects, in JavaScript, are the most important data type and form the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data types (Number, String, Boolean, null, undefined, and symbol) in the sense that these primitive data types all store a single value each (depending on their types).

While these primitive data types can each hold only a single value, objects are like containers that can hold multiple values at once. These values are stored as properties of the object, each with its own key. This allows us to group related data and functions together, making our code more organised and easier to understand.

Syntax:

new Object(value)
Object(value)
let object_name = {
    key_name : value,
    ...
}

Note:- Object()  can be called with or without new. Both create a new object.

Example: Below is an example of Objects in JavaScript.

Javascript
const o = new Object();
o.foo = 42;

console.log(o);
// { foo: 42 }

Output
{ foo: 42 }

Example: In this example “name”, “location”, and “established” are all “keys” and “Vivekananda School”, “Delhi” and 1971 are values of these keys respectively. Each of these keys is referred to as properties of the object. An object in JavaScript may also have a function as a member, in which case it will be known as a method of that object. Here  “displayinfo” is a method of the school object that is being used to work with the object’s data, stored in its properties.

javascript
// JavaScript code demonstrating a simple object
let school = {
    name: 'Vivekananda School',
    location: 'Delhi',
    established: '1971',
    displayInfo: function () {
        console.log(`${school.name} was established 
              in ${school.established} at ${school.location}`);
    }
}
school.displayInfo();   

Output
Vivekananda School was established 
              in 1971 at Delhi
  • Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types.
  • An object is a reference data type. Variables that are assigned a reference value are given a reference or a pointer to that value. That reference or pointer points to the location in memory where the object is stored. The variables don’t actually store the value.
  • Loosely speaking, objects in JavaScript may be defined as an unordered collection of related data, of primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and are called properties and methods, respectively, in the context of an object.

An object can be created with figure brackets {…} with an optional list of properties. A property is a “key: value” pair, where a key is a string or a symbol (also called a “property name”), and the value can be anything including numbers, strings, booleans, functions, arrays, or even other objects. .

JavaScript Object Properties

The property names can be strings or numbers. In case the property names are numbers, they must be accessed using the “bracket notation” like this.

Example: Below is the example of object properties.

javascript
let school = {
    name: 'Vivekananda School',
    location: 'Delhi',
    established: '1971',
    20: 1000,
    displayInfo: function () {
        console.log(`The value of the key 20 is ${school['20']}`);
    }
}
school.displayInfo();   

Output
The value of the key 20 is 1000

But more on the bracket notation later. Property names can also be strings with more than one space separated words. In which case, these property names must be enclosed in quotes :

let school = {
    "school name" : "Vivekananda School",
}

Example: In this example, we are accessing ‘Vivekananda’ from ‘Vivekananda School’.

javascript
// Bracket notation 
let school = {
    name: 'Vivekananda School',
    displayInfo: function () {
        console.log(`${school.name.split(' ')[0]}`);
    }
}
school.displayInfo(); // Vivekananda

Output
Vivekananda

In the above code, we made use of bracket notation and also split method provided by JavaScript which you will learn about in the strings article.

Inherited Properties

Inherited properties of an object are those properties that have been inherited from the object’s prototype, as opposed to being defined for the object itself, which is known as the object’s Own property. To verify if a property is an object’s Own property, we can use the hasOwnProperty method. Property Attributes Data properties in JavaScript have four attributes.

  • value: The property’s value.
  • writable: When true, the property’s value can be changed
  • enumerable: When true, the property can be iterated over by “for-in” enumeration. Otherwise, the property is said to be non-enumerable.
  • configurable: If false, attempts to delete the property, change the property to be an access-or property, or change its attributes (other than [[Value]], or changing [[Writable]] to false) will fail.

Example: Below is the example of inherited properties.

javascript
// hasOwnProperty code in js
const object1 = new Object();
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1')); // true

Output
true

Creating Objects: For creating objects refer to the following article. Ref:- https://www.geeksforgeeks.org/?p=190694

Accessing Object Members

Object members(properties or methods) can be accessed using the dot notation

(objectName.memberName);

Example: Below is the example of accessing object members.

javascript
let school = { 
    name : "Vivekanada", 
    location : "Delhi", 
    established : 1971,
    20 : 1000, 
    displayinfo : function() { 
        console.log(`${school.name} was established 
        in ${school.established} at ${school.location}`); 
    } 

} 
console.log(school.name); 

console.log(school.established); 

Output
Vivekanada
1971

Bracket Notation

Syntax:

 objectName["memberName"]

Example: Below is the example of Bracket Notation.

javascript
let school = {
    name: "Vivekanada School",
    location: "Delhi",
    established: 1995,
    20: 1000,
    displayinfo: function () {
        document.write(`${school.name} was established 
        in ${school.established} at ${school.location}`);
    }
}

// Output : Vivekanada School 
console.log(school['name']);

// Output: 1000 
console.log(school['20']); 

Output
Vivekanada School
1000

Unlike dot notation, the bracket keyword works with any string combination, including, but not limited to multi-word strings.

somePerson.first name // invalid
somePerson["first name"] // valid

Unlike dot notation, bracket notation can also contain names that are the results of any expressions variables whose values are computed at run-time.

let key = "first name" somePerson[key] = "Name Surname"

Similar operations are not possible while using the dot notation.

Iterating over all keys of an object

To iterate over all existing enumerable keys of an object, we may use the for…in construct. It is worth noting that this allows us to access only those properties of an object which are enumerable (Recall that enumerable is one of the four attributes of data properties). For instance, properties inherited from the Object.prototype are not enumerable. But, enumerable properties inherited from somewhere can also be accessed using the for…in construct

Example: Below is the example.

javascript
let person = {
    gender: "male"
}

let person1 = Object.create(person);
person1.name = "Adam";
person1.age = 45;
person1.nationality = "Australian";

for (let key in person1) {
    // Output : name, age, nationality 
    // and gender
    console.log(key);
}          

Output
name
age
nationality
gender

Deleting Properties

To Delete a property of an object we can make use of the delete operator. An example of its usage has been listed below.

Example: Below is the example of deleting properties.

javascript
let obj1 = { 
    propfirst : "Name"
} 

// Output : Name 
console.log(obj1.propfirst); 
delete obj1.propfirst 

// Output : undefined 
console.log(obj1.propfirst);             

Output
Name
undefined

Example: In this example, we can not delete inherited properties or non-configurable properties

javascript
let obj1 = { 
    propfirst : "Name"
} 
// Output : Name 
console.log(obj1.propfirst) 
let obj2 = Object.create(obj1); 

// Output : Name 
console.log(obj2.propfirst); 
    
// Output : true. 
console.log(delete obj2.propfirst); 

    // Surprisingly Note that this will return true 
    // regardless of whether the deletion was successful 

    // Output : Name     
    console.log(obj2.propfirst); 

Output
Name
Name
true
Name


Previous Article
Next Article

Similar Reads

How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. There are various methods to achieve this separation
4 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below: Table of Content Using filter() with some() methodUsing filter() with includes() methodUsing filter( ) with findIndex() method
5 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
5 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing filter and includes MethodsIn this approach, we a
2 min read
How to Remove Null Objects from Nested Array of objects in JavaScript ?
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed. There are various approaches to
4 min read
What is the difference between Host objects and Native objects ?
In this article, we will learn about what are Host objects and Native objects, and their differences. JavaScript objects are broadly classified into 2 categories - native javascript objects and host javascript objects. Native objects: Native javascript objects are standard javascript objects which are provided by javascript itself. They are also kn
2 min read
Extract unique objects by attribute from array of objects
Given an array of objects and the task is to return the unique object by the attribute. Examples: Input: [ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 }, { name: 'Geeks', id: 20 }, { name: 'Geeks', id: 10 } ]Output:[ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 } ]Approach: Let's assume that name is an attribute that di
4 min read
How to Update an Array of Objects with Another Array of Objects using Lodash?
Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to update an array of objects with another array of objects in the Lodash library: Table of Content Using _.merge function from lodashUsing _.mergeWith function
2 min read
JavaScript Course Objects in JavaScript
We have learned about different Data Types that javascript provides us, most of them primitive in nature. Objects are not primitive in nature and are a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to st
4 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read