In JavaScript, objects play an important role in organizing and managing data. In this blog post, we’ll learn about JavaScript objects, their methods and their properties.
Let’s start!
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'
};
In the above example, the term ‘car’ represents an object
. Within this context, ‘color,’ ‘modelName’, and ‘yearOfManufacture’ its keys
, while the associated values
linked to these keys are ‘black’, ‘Fortuner’ and ‘2021’ respectively.
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
In JavaScript, there are the following ways to create objects.
1: Object literal
In this way, you can create an object using object literal i.e., curly braces.
Example:
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
In the above example, 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: "Mark",
lastName: "Fortner",
age: 25,
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("Mark", "Fortner");
console.log(typeof(person));
console.log(person);
Output:
object
Person {firstName: 'Mark', lastName: 'Fortner'}
3: Factory function
Factory functions are functions that return objects. You can create objects using factory functions.
For example:
function Person(firstName, lastName) {
return {
firstName: firstName,
lastName: lastName,
};
}
const person = new Person("Mark", "Fortner");
console.log(typeof(person));
console.log(person);
Output:
object
{firstName: 'Mark', lastName: 'Fortner'}
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 = "Mark";
newObject.lastName = "Fortner";
console.log(typeof(newObject));
console.log(newObject.greet());
Output:
object
Hello, I'm Mark Fortner.
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("Mark", "Fortner");
console.log(typeof(personObject));
console.log(personObject.greet());
Output:
object
Hello, I'm Mark Fortner.
You can learn more about classes here.
Object Properties
Object properties are key-value pairs. Properties allow you to store and access data within an object. Properties can usually be changed, added, and deleted.
1:Accessing Properties
You can access the properties of an object using dot notation or square brackets.
For example:
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
console.log(person.firstName); //output: Mark
console.log(person["firstName"]); //output: Mark
console.log(person.lastName); //output: Fortner
console.log(person["lastName"]); //output: Fortner
2:Modifying Properties
Objects are mutable, so you can modify the value of a property by assigning a new value to it.
For example:
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
person.firstName = "Johan";
console.log(person.firstName); //Output: Johan
3:Adding Properties
You can add new properties to an object as follows:
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
person.profession = "Developer";
console.log(person.profession); //Output: Developer
4: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
method
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
console.log(person.hasOwnProperty("age")); //Output: true
console.log(person.hasOwnProperty("city")); //Output: false
in
operator
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
console.log("age" in person); //Output: true
console.log("city" in person); //Output: false
5:Deleting Properties
You can use the delete
operator to remove a property from an object.
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
delete person.age;
console.log(person.hasOwnProperty("age")); //output: false
6:Looping through Properties
You can loop through an object’s properties using the following methods.
for...in
loop
The for…in loop iterates over the properties of an object.
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
for (const key in person) {
console.log(key + ": " + person[key]);
}
//Output:
//firstName: Mark
//lastName: Fortner
//age: 25
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 the hasOwnProperty
method.
For example:
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
};
for (const key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ": " + person[key]);
}
}
//Output:
//firstName: Mark
//lastName: Fortner
//age: 25
Object.keys
This method returns the array of keys of an object.
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
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: "Mark",
lastName: "Fortner",
age: 25
};
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: "Mark",
lastName: "Fortner",
age: 25
};
const values = Object.values(person);
console.log(values);
//Output:
//['Mark', 'Fortner', 25]
Looping through values:
You can loop through values using for...Each
loop.
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
Object.values(person).forEach(value => {
console.log(value);
});
//Output:
//Mark
//Fortner
//25
Object.entries
This method returns the array of key-value pairs of an object.
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
const entries = Object.entries(person);
console.log(entries);
//Output:
// ['firstName', 'Mark']
// ['lastName', 'Fortner']
// ['age', 25]
Looping through keys and values:
You can loop through keys and values using for...Each
loop.
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
Object.entries(person).forEach(([key, value]) => {
console.log(key + ": " + value);
});
//Output:
//firstName: Mark
//lastName: Fortner
//age: 25
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: "Mark",
lastName: "Fortner",
age: 25,
address: {
street: "123 Main St",
city: "Anycity",
country: "UK",
contact: {
email: "mark@example.com",
phone: "9876543210"
}
},
};
console.log(person.firstName); // Output: Mark
console.log(person.address.city); // Output: Anycity
console.log(person.address.contact.email); // Output: mark@example.com
In the above example, the person
object contains a nested object called address
. address
contains another nested object called contact
. This structure allows you to access the properties of the nested objects using dot notation.
Object Destructuring
Object destructuring in JavaScript 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: "Mark",
lastName: "Fortner",
age: 25
};
console.log(person.firstName); //Ouput: Mark
console.log(person.lastName); //Ouput: Fortner
console.log(person.age); //Ouput: 25
With destructuring
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
const {firstName, lastName, age} = person;
console.log(firstName); //Ouput: Mark
console.log(lastName); //Ouput: Fortner
console.log(age); //Ouput: 25
You can also assign different variable names to the extracted properties. For example:
const person = {
firstName: "Mark",
lastName: "Fortner",
age: 25
};
const {firstName: fName, lastName: lName, age} = person;
console.log(fName); //Ouput: Mark
console.log(lName); //Ouput: Fortner
console.log(age); //Ouput: 25
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: "Mark",
lastName: "Fortner"
};
const object2 = {
subject: "English",
marks: 86
}
const newObject = {
...object1,
...object2
};
console.log(newObject);
// Output: {firstName: 'Mark', lastName: 'Fortner', 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}
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: "Mark",
lastName: "Fortner",
age: 25,
greet:function(){
console.log(`Hello, I'm ${this.firstName}!`)
}
};
console.log(person.greet());
//Output: Hello, I'm Mark!
Conclusion
In the preceding blog post, we’ve learned about JavaScript objects, exploring topics such as object creation, properties, nested structures, the object spread operator, object destructuring, and the use of the ‘this’ keyword.
Thanks for reading!
Keep coding!
For more content like this click here!
Follow me on X(Twitter) for daily web development tips.
Check out toast.log, a browser extension that lets you see errors, warnings, and logs as they happen on your site — without having to open the browser’s console. Click here to get a 25% discount on toast.log.
Great article. Thanks.
The beautiful imagery in X is missing here. No syntax highlight.
Can’t you use github gist?