Share
Explore

icon picker
Using JavaScript Objects in your code - A Beginner’s Guide.

about-us-male

Reader Persona

Alok is a beginner web developer who is trying to use JS to scale his website or web app. He has used jQuery and Bootstrap JS snippets before to use JS but has never used JS objects in his code. He doesn’t see why a JS object or OOP is needed.
Working with objects in JavaScript might seem unnecessary if you are only using JS for toggling tabs, making pop-ups or for other basic DOM Manipulation tricks.
However, if you’re planning to use JavaScript seriously in your code or learn JS frameworks like Node JS, Express or React, then it is better to understand how JavaScript Objects work.

So, What is a JavaScript Object?

In JavaScript, an Object is a data type which can store multiple values that are related to each other.
JavaScript object is used to store related data and functions together.
The “object” then can be reused whenever you need it.
This eliminates the need to redeclare variables or functions for the same operation later in the code, making your code cleaner and more readable with fewer lines.

Comparing JavaScript Objects with real-world objects.

If you’re a beginner, it is hard to visualize the concept of Object or Object Oriented Programming (OOP).
However, we can imagine a JavaScript Object as a real-world object for simplification purposes. This can help you understand the benefits of using objects.
Let’s suppose you have two cars a Toyota and a Honda. All cars have some attributes associated with them that make them a “car”. For instance, both cars have a model and a color.

1. Using Primitive Data Type Vs. Object Data Type for grouping related data.

You can use primitive data types like “var” to store the model and color of your cars in your code like this:
Primitive data type “var” to store data.
var toyotaModel = "Camry";
var toyotaColor = "Green";
var hondaModel = "Civic";
var hondaColor = "Silver";
Or, you can organize the above data using an object data type like this
Object data type to store and group related data.
const toyota = {
model: "Camary",
color: "Green"
};
const honda = {
model: "Civic",
color: "Silver"
}
As you can see, using Object data type helps us to group the related data making the code more readable and organized. The attributes by which the two objects are grouped are the same: “model” and “color”. In OOP, these attributes are referred to as Properties

2. Constructing multiple objects using Constructors.

We can agree that both Toyota and Honda can be classified as “Car” because both of them share the same properties. In JavaScript, if you have to add multiple objects that share the same property, we can use constructors.
Constructor is a JavaScript function that acts as a template to construct multiple objects.
This will help us to further organize and clean our code. It also helps in reusability.
Using the Constructor Function to create a template for Car objects
//Constructor Function
function Car(model, color) {
this.model = model;
this.color = color;
}

//Constructing new objects with the help of Car constructor
const toyata = new Car("Camry", "Green");
const honda = new Car("Civic", "Silver");
const ford = new Car("Mustang", "Red");

// Log this in your console
console.log(toyata.color); // Green
console.log(honda.color); // Silver
console.log(ford.color) // Red
Here, in just a few lines of code, we were able to create 3 Car objects using the Car constructor. The console.log functions will print Green, Silver and Red respectively in the console. The dot operator . is used to return the value of an object’s property.
Here, the new keyword is necessary to call a Constructor function.
Note: When declaring a constructor function, we Capitalize the first letter of the identifier: “C” in “Car”.

3. What is a JavaScript Method and why it is used?

JavaScript method is simply a function that is assigned as an object’s property.
It means you can assign a function as a value of a property and can call it just like a property using the . operator. You can put a function inside an object’s property like this:
const toyata = {
model: "Camry",
color: "Green",
startEngine: function() {
console.log (this.model,": Engine started.");
},
}

// Calling the StartEngine method
toyata.startEngine(); // Output: Camry: Engine started.
Here, you can see that the startEngine is a property that has a function inside it. In JavaScript, a property like startEngine is known as a method.
Creating Methods in Constructor for reusability
Like we created a method in an object, we can also create a method in a Constructor function so that all the objects created by the constructor can inherit the method.
function Car (model, color) {
this.model = model;
this.color = color;
this.startEngine = function() {
console.log (this.model,": Engine started.");
}

this.checkCarColor = function(){
console.log("The car's color is: ", this.color);
}
}

// Creating instances (object) of Car
const toyata = new Car("Camry", "Green");
const honda = new Car("Civic", "Silver");

toyata.startEngine(); // Output: Camry: Engine started.
toyata.checkCarColor(); // Output: The car's color is: Green

honda.startEngine(); // Output: Civic: Engine started.
honda.checkCarColor(); // Output: The car's color is : Silver
In the above code, we can see how the same methods can be used by all the objects created by Car constructor functions.

Do you “need” to use JS Objects in your code?

Yes. In fact, you might be already using objects without realizing it. In JavaScript, almost everything is a property or a method of an object. These are some common JS Objects that are widely used:

1. Document object

If you are using JavaScript for basic DOM Manipulation like changing text colors or show/hide texts, you are probably using document.querySelector document.getElementbyId document.AddEventListener . These are all methods of document object. A Document is a built-in JavaScript object that is created when the browser loads an HTML Document.

2. Window object : Understanding alert() method.

Most of us have used the alert('Lorem Ipsum'); function when we first discovered JavaScript. This is actually a method of a global object called window. Since the window object runs on the global scope, we can directly call the method without referencing window . The actual code looks like this:
window.alert('Lorem Ipsum');

3. Console object

The console object is an in-built object in JavaScript that is used to pass arguments to the system console (terminal, command prompt). Here are some common console methods that are regularly used while debugging JS code.
console.log("Check this code");
console.error("There is an error");
console.warn("This is a warning");
console.info("This is an info");

4. JS Arrays

This might come as a surprise to many, but in JavaScript, every Array you create is an object.
Creating Array object using Array Literals
let fruits = ['Apple', 'Orange'];
Creating Array object using in-built Array constructor function
let fruits = new Array('Apple', 'Orange');
In both examples above, JavaScript treats the array as an object. That is the reason you can use methods like these in any JS arrays:
// push method is used to add an element at the end of an Array object
fruits.push('Banana');

// length method is used to get the total number of elements in an array object
let arrayLength = fruits.length();

What else do you “need to know” about JavaScript objects?

The above are some basics of JS objects. There are more topics to explore about JS Objects. The JavaScript ECMAScript 6 (ES6) version allows the use of Class in JavaScript. This makes JavaScript code more similar to other OOP languages like C++ or Java.
What’s a JS Prototype?
Using Classes in JS ES6.
Looping Objects in JS
Spread operators in JS

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.