What Is Object In JavaScript – The Complete Guide 2022

When most people think of JavaScript, they think of it as a language used to create dynamic web pages. But there’s so much more to JavaScript than that! In fact, JavaScript is a full-fledged programming language that you can use to create all sorts of things, from simple scripts to complete applications.

One of the most important concepts in programming is the idea of an object. An object is a collection of data values (called properties) and functions (called methods) that work together to perform some task. In JavaScript, objects are used to represent just about everything – from simple values like strings and numbers, to more complex things like arrays and dates.

In this article, we’ll take a closer look at objects in JavaScript, and learn how to create and use them. Let’s get started!

Objects Overview

diagram explaining the components of object in javascript

Just like any other programming language, Objects in JavaScript can be compared with real life objects.

In JavaScript, an object is a collection of properties, each of which has a name and a value. Properties can be either data values (like strings and numbers) or methods (functions that perform some task).

Compare this to a user that writes blogs on a website. The user object might have properties like name, email, website, age, location, and blogs written by the person. It might also have a method for creating new blog posts.

Object Properties

All objects have properties. A property is just a name for a value that’s stored inside an object.

Each property has two parts:

1. The property name (also called the key), which is used to identify the property.

2. The property value, which can be any data type (including another object).

Here’s an example of a simple object that has two properties:

let user = {

name: "Kelly",

age: 30

};

In the example above, we have created an object called user with two properties: name and age. The property names are “name” and “age”, and the property values are “Kelly” and 30, respectively.

The value of a property need not be a primitive data type like a string or number. It can also be another object. In fact, an object can even have a property whose value is itself!

For example, our user object might have a property called address, whose value is an object that represents the user’s physical address. This nested object might have its own properties, like street, city, state, and zip code.

let user = {

name: "Kelly",

age: 30,

address: {

street: "123 Main St",

city: "New York",

state: "NY"

}

};

The value of a property might even be an array. For example, our user object might have a property called interests, whose value is an array of strings that represent the things the user is interested in.

let user = {

name: "Kelly",

age: 30,

address: {

street: "123 Main St",

city: "New York",

state: "NY"

},

interests: ["music", "skiing"]

};

Related Read: What Is Class In JavaScript?

JavaScript Object Methods

The various methods of Object are –

1. hasOwnProperty() – This method returns a boolean value that indicates whether the object has the specified property or not.

2. isPrototypeOf() – This method returns a boolean value that indicates whether the object on which it is called is in the prototype chain of the specified object.

3. propertyIsEnumerable() – This method returns a boolean value that indicates whether the specified object has the specified property and whether that property is enumerable.

4. toString() – This method returns a string representation of the object.

5. valueOf() – This method returns the primitive value of the specified object.

These methods can be used directly on the Object constructor to get information about objects or modify them in some way –

let user = {

name: "Kelly",

age: 30,

address: {

street: "123 Main St",

city: "New York",

state: "NY"

},

interests: ["music", "skiing"]

};

user.hasOwnProperty("name"); // returns true

user.propertyIsEnumerable("name"); // returns true

Object.prototype.isPrototypeOf(user); // returns true

user.toString(); // "[object Object]"

user.valueOf(); // return the object

Creating Custom Objects In JavaScript

Using The New Keyword

When we create new objects, we use the new keyword:

let user = new Object();

user.name = "Kelly";

user.email = "[email protected]";

user.age = 30;

console.log(user); // { name: "Kelly", email: "[email protected]", age: 30 }

As you can see, this creates a new object with the specified properties.

Using Object Literals

We can also create objects using object literals:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs : ["how to be successful in life", "how to travel in New York on a budget"],

greet(){

  console.log(`Hello ${this.name}!`);

}

};

console.log(user); // { name: "Kelly", email: "[email protected]", age: 30, location: "New York", blogs: ["how to be successful in life", "how to travel in New York on a budget"], greet: function (){ console.log(`Hello ${this.name}!`); }}

As you can see, this creates an object with the specified properties and methods.

Using Constructor Functions

We can also create objects using constructor functions:

function User(name, email, age){

this.name = name;

this.email = email;

this.age = age;

}

let kelly = new User("Kelly", "[email protected]", 30);

console.log(kelly); // User {name: "Kelly", email: "[email protected]", age: 30}

As you can see, this creates a new object with the specified properties using the User constructor function.

Object Literals

Object literals are a simple way to create objects. An object literal is just a set of comma-separated name/value pairs, enclosed in curly braces ({}).

For example, let’s say we want to create an object that represents a user that writes some blogs on her website. We could do this using an object literal:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

As you can see, each property has a name (like name, email, age, etc.) and a value (like ‘Kelly’, ‘[email protected]’, 30, etc.). In addition, the object literal syntax allows us to create methods as well.

For example, let’s say we want to add a method called login that displays a message that the user has logged in. We can do this by adding a function as the value of the login property:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"],

login: function(){

console.log("the user has logged in");

}

};

Now that we’ve seen how to create objects using object literals, let’s take a look at some of the things we can do with them.

Accessing Object Properties

Once we have created an object, we can access its properties using two methods – dot notation and bracket notation.

Dot Notation

Dot notation is the most common way to access object properties. To use dot notation, we simply write the name of the object, followed by a dot (.), followed by the property name:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

console.log(user.name); // Kelly

In the example above, we have created an object called user with several properties. We access the name property using dot notation, and print it to the console.

Bracket Notation

We can also use bracket notation to access object properties. With bracket notation, we write the name of the object, followed by a set of square brackets ([ ]), followed by the property name inside quotation marks:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

console.log(user["name"]); // Kelly

As you can see, we get the same result when we use bracket notation as when we use dot notation. Notice that we are using a quote-delimited string inside the square brackets – this is necessary because property names can contain spaces and other characters that are not valid in JavaScript identifiers.

There are some situations where bracket notation is necessary. For example, if we want to assign a variable to a property of an object, we have to use bracket notation:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

const key = "name";

console.log(user[key]); // Kelly

In the example above, we have created a variable called key and assigned it the string ‘name’. We access the name property of our user object using bracket notation and the key variable.

We can’t do this using the dot notation because the dot notation requires us to write the property name directly:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

const key = "name";

console.log(user.key); // undefined

As you can see, when we try to access the user object’s name property using the key variable with dot notation, we get an undefined result. This is because the key variable contains the string ‘name’, not the actual name property of the user object.

Another situation where we have to use bracket notation is when we want to access a property that has a space in its name:

let user = {

  name : "Kelly",

  "email address" : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

console.log(user["email address"]) // [email protected]

As you can see, we use bracket notation to access the user object’s email address property.

Updating Object Properties

We can update object properties in much the same way as we access them. We can use either dot notation or bracket notation:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

// using dot notation

user.age = 35;

console.log(user.age); // 35

// using bracket notation

user["location"] = "Los Angeles";

console.log(user["location"]); // Los Angeles

As you can see, we can use either dot notation or bracket notation to update properties of an object.

Adding New Properties To An Object

We can add new properties to an object in much the same way as we update existing properties. We can use either dot notation or bracket notation:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

// using dot notation

user.occupation = "teacher";

console.log(user.occupation); // teacher

// using bracket notation

user["hobbies"] = ["cooking", "reading"];

console.log(user["hobbies"]); // ["cooking", "reading"]

As you can see, we can use either dot notation or bracket notation to add new properties to an object.

Deleting Properties From An Object

We can delete properties from an object using the delete keyword:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

delete user.age;

console.log(user); // { name: "Kelly", email: "[email protected]", location: "New York", blogs: ["how to be successful in life", "how to travel in New York on a budget"] }

As you can see, we have deleted the age property from our user object.

Checking If An Object Property Exists

Sometimes we want to check if an object has a certain property before we try to access or update it. We can do this using the in keyword:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

console.log("age" in user); // true

console.log("occupation" in user); // false

As you can see, the in keyword returns a boolean value depending on whether the object has the specified property.

Another way to check if an object has a certain property is to use the typeof operator:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"]

};

console.log(typeof user.age); // number

console.log(typeof user.occupation); // undefined

As you can see, the typeof operator returns a different value for properties that exist and properties that don’t exist.

Object Methods

Methods are functions that belong to objects. They are very similar to the functions we’ve seen so far, with a few key differences.

First of all, methods are always invoked (called) using dot notation:

let user = {

  name : "Kelly",

  email : "[email protected] ",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"],

greet(){

  console.log("Hello there!");

}

};

user.greet(); // Hello there!

As you can see, we use dot notation to invoke the greet method.

Another key difference is that methods have access to the properties of the object they belong to. This means that they can read and update those properties:

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"],

greet(){

  console.log(`Hello ${this.name}!`);

}

};

user.greet(); // Hello Kelly!

As you can see, the greet method has access to the user object’s name property. This is because the ‘this’ keyword refers to the object that the method belongs to.

This keyword is a very important concept in JavaScript, so let’s learn more about it.

‘This’ Keyword

This keyword in JavaScript refers to the object that is currently being executed. In the global scope, this refers to the global object. In a function, this refers to the object that invoked the function. In an event, this refers to the element that received the event.

If you use this keyword outside of an object, it will refer to the global object. You can also use this keyword inside of an arrow function. When used inside of an arrow function, this keyword will refer to the object that invoked the function. Arrow functions do not have this keyword. If you use this keyword inside of an arrow function, it will refer to the global object.

let user = {

  name : "Kelly",

  email : "[email protected]",

  age: 30,

  location: "New York",

  blogs: ["how to be successful in life", "how to travel in New York on a budget"],

greet(){

  console.log(`Hello ${this.name}!`);

}

};

user.greet(); // Hello Kelly!

Here, this keyword refers to the user object. This means that we can access the user object’s properties using this keyword.

Prototypes

Every object in JavaScript has a prototype. The prototype is an object that contains properties and methods that are inherited by the object.

For example, let’s say we have a Person constructor:

function Person(name, age){

this.name = name;

this.age = age;

}

And we create a new Person object:

let person1 = new Person("John", 30);

The prototype of the person1 object would be the prototype property of the Person constructor function:

Person.prototype // {constructor: ƒ, __proto__: Object}

As you can see, the prototype object has a few properties and methods, one of which is the constructor property. This property refers back to the constructor function that created the object.

We can add properties and methods to the prototype just like we would any other object:

Person.prototype.greet = function(){

console.log(`Hello, my name is ${this.name}`);

}

person1.greet(); // Hello, my name is John

As you can see, we were able to add a greet method to the Person prototype, and then call that method on the person1 object.

Keep in mind that when we add a property or method to the prototype, it is added to all objects created by that constructor:

let person2 = new Person("Jane", 28);

person2.greet(); // Hello, my name is Jane

As you can see, both person1 and person2 have access to the greet method, even though we only added it to the prototype.

This is because when we create a new object, JavaScript checks to see if the prototype has the property or method we’re trying to access. If it does, it uses that property or method. If it doesn’t, it looks up the prototype chain until it finds the property or method.

Inheritance

Inheritance is when an object gets properties and methods from another object.

As we’ve seen, every object in JavaScript has a prototype. When we create a new object, that object inherits all of the properties and methods of its prototype.

For example, let’s say we have a Person constructor:

function Person(name, age){

this.name = name;

this.age = age;

}

And we create a new Person object:

let person1 = new Person("John", 30);

The person1 object will inherit the properties and methods of the Person prototype:

person1 // {name: "John", age: 30, __proto__: Object}

As you can see, the person1 object has the name and age properties, as well as the __proto__ property. The __proto__ property is a reference to the prototype of the object.

We can also access the prototype of an object using the Object.getPrototypeOf() method:

Object.getPrototypeOf(person1) // {constructor: ƒ, __proto__: Object}

As you can see, this returns the same object as the __proto__ property.

We can use inheritance to create a more efficient code. For example, let’s say we have a User constructor:

function User(name, email){

this.name = name;

this.email = email;

}

And we want to create a new User that has all of the properties and methods of the User constructor, plus some additional properties and methods. We can do this by creating a new constructor function that inherits from the User constructor:

function Admin(name, email){

User.call(this, name, email);

}

Admin.prototype = Object.create(User.prototype);

Admin.prototype.constructor = Admin;

As you can see, we’re using the Object.create() method to create a new object that inherits from the User prototype. We’re also setting the prototype of the Admin constructor function to be the User prototype.

We can then create a new Admin:

let admin1 = new Admin("John", "[email protected]");

console.log(admin1); // {name: "John", email: "[email protected]"}

As you can see, the admin1 object has the name and email properties of the User constructor, plus the __proto__ property.

We can also add properties and methods to the Admin prototype:

Admin.prototype.deleteUser = function(user){

// delete the user from the database

}

admin1.deleteUser(user1); // deletes the user from the database

As you can see, we were able to add a deleteUser method to the Admin prototype, and then call that method on the admin1 object.

Keep in mind that when we add a property or method to the prototype, it is added to all objects created by that constructor:

let admin2 = new Admin("Jane", "[email protected]");

admin2.deleteUser(user1); // deletes the user from the database

As you can see, both admin1 and admin2 have access to the deleteUser method, even though we only added it to the prototype.

This is because when we create a new object, JavaScript checks to see if the prototype has the property or method we’re trying to access. If it does, it uses that property or method. If it doesn’t, it looks up the prototype chain until it finds the property or method.

Inheritance is a powerful tool that can help us create more efficient code. It’s important to understand how prototypes and inheritance work in order to take full advantage of them.

Getters And Setters

In JavaScript, we can create getters and setters to define how a property is accessed and modified.

A getter is a function that is called when we try to access a property of an object. A setter is a function that is called when we try to modify a property of an object.

For example, let’s say we have an object with a firstName and lastName property:

let person = {

firstName: "John",

lastName: "Doe",

}

If we try to access the firstName property, JavaScript will call the getter function:

person.firstName // "John"

As you can see, this prints the value of the firstName property.

We can define a getter function like this:

let person = {

firstName: "John",

lastName: "Doe",

get fullName(){

return this.firstName + " " + this.lastName;

}

}

As you can see, we’re using the get keyword to define a getter function. We’re also returning the value of the firstName and lastName properties.

Now when we try to access the fullName property, JavaScript will call the getter function:

person.fullName // "John Doe"

As you can see, this prints the value returned by the getter function.

We can also define a setter function like this:

let person = {

firstName: "John",

lastName: "Doe",

get fullName(){

return this.firstName + " " + this.lastName;

},

set fullName(value){

let parts = value.split(" ");

this.firstName = parts(0);

this.lastName = parts(1);

}

}

As you can see, we’re using the set keyword to define a setter function. We’re also splitting the value parameter into an array of two parts, and setting the firstName and lastName properties to those values.

Now when we try to modify the fullName property, JavaScript will call the setter function:

person.fullName = "Jane Doe";

console.log(person); // {firstName: "Jane", lastName: "Doe"}

As you can see, this modifies the firstName and lastName properties.

Getters and setters are a convenient way to define how a property is accessed and modified. They’re especially useful when we need to perform some sort of calculation or validation when a property is accessed or modified.

Comparing Objects

In JavaScript, we can compare two objects to see if they’re equal.

For example, let’s say we have two objects with the same properties and values:

let obj1 = {

name: "John",

age: 30,

}

let obj2 = {

name: "John",

age: 30,

}

If we try to compare these two objects, we’ll get false:

obj1 == obj2 // false

This is because JavaScript compares object references, not values. In other words, it checks to see if both objects are referencing the same location in memory. Since these are two different objects, they’re not referencing the same location in memory, so JavaScript returns false.

However, we can compare the values of two objects like this:

let obj1 = {

name: "John",

age: 30,

}

let obj2 = {

name: "John",

age: 30,

}

function isEqual(a, b) {

return JSON.stringify(a) === JSON.stringify(b);

}

If we try to compare these two objects now, we’ll get true:

isEqual(obj1, obj2); // true;

This is because the JSON.stringify() method converts an object to a string, and we’re comparing the two strings to see if they’re equal.

Cloning Objects

In JavaScript, we can clone an object by using the spread operator:

let obj1 = {

name: "John",

age: 30,

}

let obj2 = {…obj1};

console.log(obj2); // {name: "John", age: 30}

As you can see, this creates a new object with the same properties and values as the original object.

Predefined Objects

There are some predefined Objects in JavaScript which can come very handy. Let’s have a look at these methods and their use cases.

Math Object

The Math object is a predefined object that has properties and methods for mathematical constants and functions.

For example, we can use the Math.PI property to get the value of pi:

console.log(Math.PI); // 3.141592653589793

We can also use the Math.round() method to round a number to the nearest integer:

console.log(Math.round(4.7)); // 5

Date Object

The Date object is a predefined object that stores date and time information.

For example, we can use the Date() constructor to create a new Date object:

let now = new Date();

console.log(now); // 2022-03-28T10:09:27.353Z

We can also use the getFullYear() method to get the current year:

console.log(now.getFullYear()); // 2022

String Object

The String object is a predefined object that stores string information.

For example, we can create a new String object like this:

let str = new String("Hello");

console.log(str); // Hello

And we can use the toUpperCase() method to convert a string to uppercase:

console.log(str.toUpperCase()); // HELLO

Array Object

The Array object is a predefined object that stores array information.

For example, we can create a new Array object like this:

let arr = new Array(1, 2, 3);

console.log(arr); // 1,2,3

And we can use the forEach() method to loop through an array:

arr.forEach((item) => {

console.log(item);

});

// 1

// 2

// 3

As you can see, this logs each item in the array to the console.

This is just a brief overview of some of the predefined objects in JavaScript. There are many more, and I encourage you to explore them on your own.

Leave a Reply