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

Objects in Javascript

Last Updated : 14 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Objects in JavaScript are the most important data type and form the building blocks for modern JavaScript. Unlike primitive data types (Number, String, Boolean, null, undefined, and symbol), which hold a single value, objects can hold multiple values as properties. This makes objects incredibly useful for grouping related data and operations, leading to more organized and maintainable code.

What Are Objects in JavaScript?

In JavaScript, an object is a collection of related data and functions, known as properties and methods, respectively. Properties are “key: value” pairs that store data, while methods are functions associated with the object that can manipulate its properties.

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. .

Objects as Reference Types

Objects in JavaScript are reference types. This means that when you assign an object to a variable, the variable holds a reference (or pointer) to the memory location where the object is stored, not the actual object itself.

JavaScript Object Properties

Properties are defined as key-value pairs, where the key is a string or symbol and the value can be any data type, including numbers, strings, booleans, functions, arrays, or other objects.

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

JavaScript objects can inherit properties from their prototypes. These are known as inherited properties. To check if a property is an object’s own property (not inherited), you can use the hasOwnProperty method.

Example:

JavaScript
let school = {
    "name": "Vivekananda School"
};
console.log(school.hasOwnProperty("name")); 
console.log(school.hasOwnProperty("toString"));

Output
true
false

Property Attributes

In JavaScript, each property has attributes that define its behavior:

  1. value: The property’s value.
  2. writable: When true, the property’s value can be changed
  3. enumerable: When true, the property can be iterated over by “for-in” enumeration. Otherwise, the property is said to be non-enumerable.
  4. 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 of Property Attributes:

javascript
let person = {
    name: "John"
};
Object.defineProperty(person, 'name', {
    writable: false,
    enumerable: true,
    configurable: false
});

Creating Objects: For creating objects refer to the following article. Ref: Creating objects in JavaScript

Accessing Object Members

Object members (properties or methods) can be accessed using dot notation or bracket 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 enumerable properties of an object, you can use the for…in loop. This loop will iterate over both the object’s own properties and any enumerable properties it has inherited.

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, use the delete operator. Note that you cannot delete inherited properties or non-configurable properties.

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

Understanding objects in JavaScript is essential for effective programming. They enable you to create complex data structures and perform a variety of operations. For more advanced JavaScript tutorials and examples, explore our JavaScript Tutorial and JavaScript Examples.



Previous Article
Next Article

Similar Reads

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
7 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 reduce MethodUsing Set for Efficient FilteringUsi
3 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
8 min read
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
5 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
7 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 updating an array of objects with another array of objects in the Lodash library: Table of Content Using lodash _.merge() function Using lodash _.mergeWith()
4 min read
How to Convert Object Containing Objects into Array of Objects using Lodash?
Lodash is a JavaScript utility library that provides predefined functions to make code more readable and cleaner. These functions are optimized for performance, often being faster than native JavaScript methods for complex operations.We will learn how to convert an object containing objects into an array of objects using Lodash. There are two appro
3 min read
Get list of Duplicate Objects in an Array of Objects
Finding duplicates in an array of objects is a common task in JavaScript, especially when dealing with data manipulation and validation. This will guide you through the process of identifying duplicate objects in an array using various techniques. Understanding the ProblemLet's assume we have an array of objects where each object has a set of key-v
4 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
How to merge properties of two JavaScript objects dynamically?
Using Spread Operator: Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows the privilege to obtain a list of parameters from an array. Javascript objects are key-value paired dictionaries. We can merge different obje
1 min read
Max/Min value of an attribute in an array of objects in JavaScript
In this article, we are given an array of objects and the task is to get the maximum and minimum values from the array of objects. For this approach, we have a few methods that will be discussed below. Methods to get Min/Max values:using JavaScript apply() and Array map()using JavaScript Array reduce() Methodusing JavaScript loopsMethod 1: Using Ja
3 min read
JavaScript | Date Objects
The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970. But using another methods we can only get and set the
4 min read
How to Sort/Order keys in JavaScript objects ?
Given an object and the task is to sort the JavaScript Object on the basis of keys. Here are a few of the most used techniques discussed with the help of JavaScript. Approach 1: By using .sort() method to sort the keys according to the conditions specified in the function and get the sorted keys in the array. To copy the whole object to that tempor
3 min read
JavaScript | window.location and document.location Objects
window.location and document.location: These objects are used for getting the URL (the current or present page address) and avert browser to a new page or window. The main difference between both is their compatibility with the browsers. The window.location is read/write on all compliant browsers. The document.location is read-only in Internet Expl
2 min read
How to check two objects have same data using JavaScript ?
In JavaScript, we cannot directly compare two objects by equality operators (double equals == or triple equals ===) to see whether they are equal or not. Comparing two objects like this results in false even if they have the same data. It is because those are two different object instances, they are referring to two different objects. There is no d
2 min read
How to convert CSV string file to a 2D array of objects using JavaScript ?
A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format. In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript. Given a comma-separated values (CSV) string to a 2D array, using Javascript
4 min read
Write a program to convert an array of objects to a CSV string that contains only the columns specified using JavaScript
When we want to store multiple values in one variable then instead of a variable, we use an array. which allows you to store multiple types of data for example you could have a string, an integer, etc. In this article, we will learn to convert the array objects to CSV string data. Given array objects ( key: value ) to CSV string comma-separated val
3 min read
How to loop through a plain object with the objects as members in JavaScript ?
Looping through a plain JavaScript object with objects as members means iterating over each property of the object and accessing its values, which may also be objects. This is a common task in JavaScript, especially when dealing with JSON data or APIs. There are several ways to loop through a plain JavaScript object with objects as members. Here ar
3 min read
How to create an array with multiple objects having multiple nested key-value pairs in JavaScript ?
In this article, we will learn to create an array with multiple objects having key-value pairs, we will use nesting which means defining another array in a pre-defined array with key-value pairs. Suppose we have several arrays of objects means containing various key-value pairs where keys are uniquely identified now we have to add these arrays to a
3 min read
How to Preserve Immutability of Objects in JavaScript ?
Immutability is an issue when it comes to private or restricted objects. Sometimes we need to create new objects without making modifications or changes unintendedly to preserve the integrity of data. That's why, we need to find a way to preserve the object states. In this article, we will understand the immutability of objects concept, along with
3 min read
Difference Between Objects and Prototypes in JavaScript
Objects in JavaScriptThe Objects in JavaScript are instances of the class or constructors and they can hold properties and methods. These properties and methods can be unique to the object or inherited from the prototypes. The Objects can be created using the constructor functions, object literals, or Object constructors. Syntax:const person = { na
3 min read
Difference between Array and Array of Objects in JavaScript
ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored in an array. Example: In thi
3 min read
Difference Between Variables and Objects in JavaScript
The variables and objects are fundamental concepts but they serve different purposes. The Variables are used to store data values while objects are used to group related data and functions into a single entity. JavaScript VariableA variable in JavaScript is a named container that stores a value. It can be created using the var, let, or const. Synta
2 min read
Flatten JavaScript objects into a single-depth Object
Given a nested JavaScript object, the task is to flatten the object and pull out all the values to a single depth. If the values are already at a single depth then it returns the result unaltered. typeof() method: The typeof() method is used in the script to check the type of JavaScript variable. Syntax:typeof(variable);Parameters: Variable: The in
2 min read
How to find property values from an array containing multiple objects in JavaScript ?
To find property values from an array containing multiple objects in JavaScript, we have multiple approaches. In this article, we will learn how to find property values from an array containing multiple objects in JavaScript. Several methods can be used to find property values from an array containing multiple objects. Table of Content Using for-lo
4 min read
Classes and Objects in JavaScript
Classes Classes were first introduced in the new version of the ES6 classes which replaced the previously used functions. Class is nothing but a blueprint for an object of it. It is used to create an object mainly. If we relate it to a real-life example then it is like a plan for a building or house where that plan contains details about doors, win
4 min read
What is LocalStorage & SessionStorage Objects in JavaScript ?
LocalStorage and sessionStorage are Web Storage API objects in JavaScript for key-value data storage. localStorage persists data across browser sessions, while sessionStorage is limited to the current session, clearing on browser/tab closure. Both are associated with the origin and provide simple ways to store and retrieve data. Some methods are us
1 min read