What are JavaScript Objects?
In JavaScript, objects allow you to store and organize data in a structured way. Objects are collections of key-value pairs, where each key is a string, symbol or number and each value can be of any data type, including other objects, functions, and primitive values.
For example, think of a car. It’s an object, with the properties like color, model and manufacture year.
// object
const car = {
color: "black",
modelName: "Fortuner",
yearOfManufacture: "2021",
};
Here, the term car
represents an object. The keys are color
, modelName
, and yearOfManufacture
, and their corresponding values are "black", "Fortuner", and "2021".
To put it simply, a JavaScript object is like a container that lets you store and organize properties and methods related to something.
Objects are used for representing complex data structures, organizing code, and creating classes and instances through object-oriented programming.
Creating Objects
JavaScript provides the following ways to create objects.
1. Object literal
You can create an object using the object literal syntax (curly braces {}
).
Example:
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
};
Here, person
is an object with the properties such as firstName
, lastName
and age
.
You can also add functions to the object.
For example:
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
greet: function () {
alert("Hello World");
},
};
2. Constructor function
This is the most used way to create objects. Using new
keyword, the constructor function allows creation of multiple objects.
For example:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const person = new Person("Shefali", "Jangid");
console.log(typeof person); // Output: object
console.log(person); // Output: Person {firstName: 'Shefali', lastName: 'Jangid'}
Here,
Person
is a constructor function. By convention, constructor function names start with a capital letter.- Using
new
creates a new object and setsthis
to it. this.firstName = ...
adds properties to that object.- So
person
becomes:{ firstName: "Shefali", lastName: "Jangid" }
typeof person
is "object".
3. Factory function
Factory functions are functions that return objects, so they are used to create objects.
For example:
function Person(firstName, lastName) {
return {
firstName: firstName,
lastName: lastName,
};
}
const person = Person("Shefali", "Jangid");
console.log(typeof person); // Output: object
console.log(person); // Output: {firstName: 'Shefali', lastName: 'Jangid'}
4. Object.create()
Using Object.create()
method, you can create a new object using an existing object as the prototype for the newly created object.
For example:
const existingObjectPrototype = {
greet: function () {
console.log(`Hello, I'm ${this.firstName} ${this.lastName}.`);
},
};
const newObject = Object.create(existingObjectPrototype);
newObject.firstName = "Shefali";
newObject.lastName = "Jangid";
console.log(typeof newObject); // Output: object
console.log(newObject.greet()); // Output: Hello, I'm Shefali Jangid.
Here,
existingObjectPrototype
is a regular object with agreet
method and it will be used as the prototype for other objects.newObject
is created withexistingObjectPrototype
as its prototype. That meansnewObject
can access all methods defined inexistingObjectPrototype
.newObject.firstName = "Shefali"; newObject.lastName = "Jangid";
are own properties ofnewObject
.newObject.greet();
this method is inherited from the prototype.- Inside
greet
,this
refers tonewObject
, so it uses itsfirstName
andlastName
.
5. ES6 class syntax
You can use the class
keyword to define a constructor and methods for objects.
For example:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
greet() {
console.log(`Hello, I'm ${this.firstName} ${this.lastName}.`);
}
}
const personObject = new Person("Shefali", "Jangid");
console.log(typeof personObject); // Output: object
console.log(personObject.greet()); // Output: Hello, I'm Shefali Jangid.
Here,
Person
is aclass
.constructor()
runs automatically when you create a new instance usingnew
.greet()
is defined on the prototype and it's shared by all instances.this
refers to the current instance (personObject
here).personObject
is an instance ofPerson
.personObject
hasfirstName
,lastName
, and access to thegreet
method.
Object Properties
Object properties are key-value pairs and they allow you to store and access data within an object.
Properties can usually be changed, added, and deleted.
Accessing Properties
You can access the properties of an object using dot notation or square brackets.
For example:
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
};
console.log(person.firstName); // Output: Shefali
console.log(person["firstName"]); // Output: Shefali
console.log(person.lastName); // Output: Jangid
console.log(person["lastName"]); // Output: Jangid
Modifying Properties
Objects are mutable, that means you can modify the value of a property by assigning a new value to it.
For example:
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
};
person.firstName = "Johan";
console.log(person.firstName); // Output: Johan
Adding Properties
You can add new properties to an object as follows:
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
};
person.profession = "Developer";
console.log(person.profession); // Output: Developer
Checking the Presence of a Property
You can check if an object has a specific property using the following methods. They give the output in true
or false
.
-
hasOwnProperty
methodconst person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; console.log(person.hasOwnProperty("age")); // Output: true console.log(person.hasOwnProperty("city")); // Output: false
-
in
operatorconst person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; console.log("age" in person); // Output: true console.log("city" in person); // Output: false
Deleting Properties
You can use the delete
operator to remove a property from an object.
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
};
delete person.age;
console.log(person.hasOwnProperty("age")); // Output: false
Preventing Changes to Objects
JavaScript provides two helpful methods when you want to protect your objects from being changed.
-
Object.seal()
:The
Object.seal()
method can be used to prevent adding or removing properties from an object.You can still change the values of existing properties, but you can't add or remove any properties.
This is helpful when you need a fixed object structure but want to update the property values.
Syntax:
Object.seal(obj);
Example:
const person = { name: "Shefali", age: 26 }; Object.seal(person); // You can modify existing properties person.age = 30; // Allowed console.log(person.age); // Output: 30 // Adding or removing properties is not allowed person.profession = "Web Developer"; // Ignored delete person.name; // Ignored console.log(person); // Output: { name: "Shefali", age: 30 }
Object.isSealed()
:You can check if an object is sealed using
Object.isSealed(obj)
.Syntax:
Object.isSealed(obj);
Example:
const person = { name: "Shefali", age: 26 }; Object.seal(person); Object.isSealed(person); // Output: true
-
Object.freeze()
:The
Object.freeze()
method can be used to prevent any changes to an object, including adding, modifying or deleting properties. That means,- You can't add new properties.
- You can't change existing properties.
- You can't delete any properties.
This is helpful when you want to keep the object exactly as it is.
Syntax:
Object.freeze(obj);
Example:
const person = { name: "Shefali", age: 26 }; // Freeze the object Object.freeze(person); // Modification of the object is not allowed person.age = 30; // This won't work person.profession = "Web developer"; // This won't work console.log(person); // Output: { name: "Shefali", age: 26 }
Object.isFrozen()
:You can check if an object is frozen using
Object.isFrozen()
.Syntax:
Object.isFrozen(obj);
Example:
const person = { name: "Shefali", age: 26 }; Object.freeze(person); Object.isFrozen(person); // Output: true
Looping through Properties
You can loop through an object’s properties using the following methods.
-
for...in
loopThe
for…in
loop iterates over the properties of an object.const person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; for (const key in person) { console.log(key + ": " + person[key]); } // Output: // firstName: Shefali // lastName: Jangid // age: 26
The
for...in
loop iterates over all the properties, even the ones it gets from the prototype chain. To avoid unintended iteration over inherited properties, you can check if each property belongs only to the object by using thehasOwnProperty
method.For example:
const person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; for (const key in person) { if (person.hasOwnProperty(key)) { console.log(key + ": " + person[key]); } } // Output: // firstName: Shefali // lastName: Jangid // age: 26
-
Object.keys
This method returns the array of keys of an object.
const person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; const keys = Object.keys(person); console.log(keys); // Output: // ['firstName', 'lastName', 'age']
Looping through keys:
You can loop through keys using
for...Each
loop.const person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; Object.keys(person).forEach((key) => { console.log(key); }); // Output: // firstName // lastName // age
-
Object.values
This method returns the array of values of an object.
const person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; const values = Object.values(person); console.log(values); // Output: // ['Shefali', 'Jangid', 26]
Looping through values:
You can loop through values using
for...Each
loop.const person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; Object.values(person).forEach((value) => { console.log(value); }); // Output: // Shefali // Jangid // 26
-
Object.entries
This method returns the array of key-value pairs of an object.
const person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; const entries = Object.entries(person); console.log(entries); // Output: // ['firstName', 'Shefali'] // ['lastName', 'Jangid'] // ['age', 26]
Looping through keys and values:
You can loop through keys and values using
for...Each
loop.const person = { firstName: "Shefali", lastName: "Jangid", age: 26, }; Object.entries(person).forEach(([key, value]) => { console.log(key + ": " + value); }); // Output: // firstName: Shefali // lastName: Jangid // age: 26
Nested Objects
If you create an object, in which, an object is used as a value of the object, then this refers to a nested object. This is used for organizing and structuring complex data hierarchies.
For example:
const person = {
firstName: "John",
lastName: "Doe",
age: 26,
address: {
street: "123 Main St",
city: "Anycity",
country: "UK",
contact: {
email: "mark@example.com",
phone: "9876543210",
},
},
};
console.log(person.firstName); // Output: John
console.log(person.address.city); // Output: Anycity
console.log(person.address.contact.email); // Output: mark@example.com
Here, the person
object contains a nested object called address
. address
contains another nested object called contact
.
You can access the properties of the nested objects using dot notation like person.address.city
.
Object Destructuring
Object destructuring is a way to extract specific properties from an object and assign them to variables.
It’s a handy shortcut that lets you access object properties without typing out long dot notation every time.
For example:
Without destructuring:
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
};
console.log(person.firstName); // Output: Shefali
console.log(person.lastName); // Output: Jangid
console.log(person.age); // Output: 26
With destructuring:
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
};
const { firstName, lastName, age } = person;
console.log(firstName); // Output: Shefali
console.log(lastName); // Output: Jangid
console.log(age); // Output: 26
You can also assign different variable names to the extracted properties.
For example:
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
};
const { firstName: fName, lastName: lName, age } = person;
console.log(fName); // Output: Shefali
console.log(lName); // Output: Jangid
console.log(age); // Output: 26
Object Spread Operator
If you want to create an object by copying the properties of an existing object and adding or modifying properties as needed, then you can use the spread ...
operator.
For example:
const object = {
key1: "value1",
key2: "value2",
};
const newObject = {
...object,
key3: "value3",
};
console.log(newObject); // Output: {key1: 'value1', key2: 'value2', key3: 'value3'}
You can also merge multiple objects using the spread operator.
For example:
const object1 = {
firstName: "John",
lastName: "Doe",
};
const object2 = {
subject: "English",
marks: 86,
};
const newObject = {
...object1,
...object2,
};
console.log(newObject); // Output: {firstName: 'John', lastName: 'Doe', subject: 'English', marks: 86}
Note: When you combine objects using the spread operator, if they have properties with the same name, the properties from the last object you add will replace the ones from the earlier objects.
For example:
const object1 = {
subject: "Maths",
marks: 98,
};
const object2 = {
subject: "English",
marks: 86,
};
const newObject = {
...object1,
...object2,
};
console.log(newObject); // Output: {subject: 'English', marks: 86}
Copy Properties from Source Object to Target Object
The Object.assign()
method can be used to copy the values and properties from one or more source objects to a target object.
If a property already exists in the target object, it will be overwritten by the value from the source object.
This is helpful when you want to merge properties from multiple objects into one.
Syntax:
Object.assign(targetObject, sourceObject);
Example:
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const mergedObject = Object.assign(target, source);
console.log(mergedObject); // Output: { a: 1, b: 4, c: 5 }
You can also create a shallow copy of an object using Object.assign()
method.
const person = { name: "Shefali", age: 26 };
const cloneObject = Object.assign({}, person);
console.log(cloneObject);
// Output: { name: 'Shefali', age: 26 }
this Keyword
The this
keyword refers to the current object that a method is being called on.
It represents the object that a function or method belongs to and helps to access the object’s properties and methods from within its functions.
const person = {
firstName: "Shefali",
lastName: "Jangid",
age: 26,
greet: function () {
console.log(`Hello, I'm ${this.firstName}!`);
},
};
console.log(person.greet()); // Output: Hello, I'm Shefali!