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

JavaScript Objects

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

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 different methodologies namely Literal Form and Constructed Form.

  • Literal Form: The literal form uses the construction of object literals that can be said as a collection of key-value pairs enclosed within a pair of curly braces. The syntaxial form is shown below.
let obj = {
key1: value1,
key2: value2,
...
};
  • Constructed Form: The Constructed form uses either an object constructor function or the new keyword to create an empty object ad then adds properties to the object one by one. The syntaxial forms are shown below.
    • Object Constructor Function: In this methodology, the user creates an explicit function to take required values as parameters and assign them as the properties of the desired object.
function obj(value1, value2, ...) {
this.key1 = value1;
this.key2 = value2;
...
}
  • Using New Keyword: This methodology uses the New keyword in front of any constructor method or any built-in constructor method ( such as Object, Date, String, etc) and creates a new instance of the following object by mounting it on memory.
let obj = new Object();
obj.key1 = value1;
obj.key2 = value2;
...

Differences between using Object Literals and the Constructed Form: Both the constructed form and literal form result in creating exactly the same sort of object i.e. the end result is the same for both methodologies. The only difference between the both is that object literals can take care of several key-value pairs at once and thus is more convenient while on the other hand with the constructed-form objects, we must add the properties one-by-one in separate statements. 

Note: It is highly uncommon to use the Constructed Form over the Object Literals for creating objects, hence for any further illustrations we will be using the object literals on most occasions.

Built-In Objects:

JavaScript consists of a bunch of Built-In Objects, the following list explores most of them. Although these built-ins have the appearance of being actual types or classes like in any other OOP, in JavaScript these are only functions that can be used as constructors to create objects of the particular sub-type.

Now let us take an example to differentiate between Objects and Primitives. 

javascript
// Create string primitive.
let strPrimitive = "GeeksforGeeks";
typeof strPrimitive; // "string"
strPrimitive instanceof String; // false

// Use the Built-in String Function as Constructor.
let strObject = new String( "GeeksforGeeks" );
typeof strObject; // "object"
strObject instanceof String; // true

// inspect the object sub-type
Object.prototype.toString.call( strObject ); // [object String]

In the above example, we saw that creating a string primitive didn’t create an object or an instance of a String. Primitives are literal and immutable values, to perform tasks like calculating the length or changing any character at any position we must use the Object of type String. But JavaScript is a dynamic language and luckily for the developers, JavaScript coerces a string primitive to a String class whenever any operation needs it to be. It is to be noted, that due to internal coercion it is vastly preferred to use primitives as much as possible instead of objects.

Content of Objects:

JavaScript objects consist of a set of key-value pairs, which are known as Properties. All Properties are named in JavaScript objects and the key part represents the Property name, while the value part represents the property Value. The Property Value can be of the primitive data type or an object or even a function. The property can also be globally accessible in spite of being owned by an object. The general syntax of defining an object property is as shown below,

objectName.objectProperty = propertyValue;

The following program will clear the concepts we discussed above, 

javascript
let myObj = {
    // Integer Property.
    int_prop: 5,

    // String Property.
    str_prop: "GeeksforGeeks",

    // Object Property (Date).
    obj_prop: new Date(),

    // Object Property.
    inner_obj: {
        int_prop: 6
    },

    // Function Property.
    func_prop: function() {
        console.log("Welcome to GeeksforGeeks!");
    }
};

console.log(myObj.int_prop);
console.log(myObj.str_prop);
console.log(myObj.obj_prop.toLocaleTimeString());
console.log(myObj.inner_obj.int_prop);
myObj.func_prop();

Output:

5
GeeksforGeeks
5:47:55 PM
6
Welcome to GeeksforGeeks!

As per conventions, functions associated with an object are known as methods. This is considered to be a small difference between a function and a method. A function is an independent sequence of a bunch of statements whereas a method is associated with an object and is generally referenced by this keyword

Defining Global Variables to be owned by Objects: This is mostly done on methods, the process is fairly simple we will define our function as we are used to, and while defining the function to be a member of the object properties we will just give the name of the function as the value of one key. Let us see the example given below. 

javascript
// Define Function Explicitly.
function toGreet() {
    console.log("Hello There!");
}

let myObj = {

    // Mention Function-Name as Value.
    greet: toGreet,

    // Define Function implicitly.
    byWhom: function() {
        console.log(" - GeeksforGeeks.org");
    }
}

myObj.greet();
myObj.byWhom();

Output:

Hello There!
- GeeksforGeeks.org

Note: The ‘with’ keyword can be used to reference an object’s properties. The object specified as an argument to with becomes the default object for the duration of the block that follows. This is generally recommended not to be used by developers. The use of with is not allowed in JavaScript strict mode. 

Important Points:

  • Date values can only be created with their constructed object form, as they have no literal form.
  • Objects, Arrays, Functions, and RegExps (regular expressions) are all objects regardless of their creation methodologies i.e. whether the literal or constructed form was used to create them.
  • The constructed form may offer more customization while creating an object, this is the sole advantage over using the literal form.

With this, we can end this discussion about Objects in JavaScript and can start walking on the Path of defining and describing important topics related to objects.

JavaScript Objects – FAQs

What is an object in JavaScript?

An object is a complex data structure that allows you to store collections of data. It is used to group related data and functionality together, consisting of properties (key-value pairs) and methods (functions).

How do you create an object in JavaScript?

You can create an object using object literals, the new Object() syntax, or by using constructor functions and classes.

What is an object literal?

An object literal is a comma-separated list of key-value pairs wrapped in curly braces. It is the most common way to create objects.

How do you access object properties?

You can access object properties using dot notation or bracket notation. Dot notation is typically used when you know the exact name of the property, while bracket notation is useful when the property name is dynamic or not a valid identifier.

How do you add or modify properties in an object?

You can add or modify properties using dot notation or bracket notation. Assign the new value to the property, whether it exists or not.

How do you delete properties from an object?

You can delete properties using the delete operator, which removes the property from the object.



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