JavaScript Objects: A Step-by-Step Tutorial for Beginners

Milos BabicMilos Babic
2 min read

In class-based programming languages like Java or C#, you must create a class before instantiating an object. Simply put, a class is a blueprint for creating objects because it holds attributes and methods that future instances will have.

On the other hand, JavaScript doesn’t require classes to instantiate an object. You can create objects using classes, but you don’t have to. This language is more flexible than many others and provides several different ways to create objects.

JavaScript objects are a collection of data represented as key-value pairs. Keys must be strings (or will be implicitly converted to strings). However, values can be numbers, strings, functions, other objects, or evaluated expressions.

How to Create JavaScript Objects?

There are three main ways to create a JavaScript object:

Step 1: Object Literal Syntax

This is the easiest way to create an object in JavaScript. Wrap your keys and values with curly braces {} and separate them with commas:

let user = {
  firstName: "Marko",
  lastName: "Jovanović",
  age: 30
};

Don’t forget to put ; after the curly braces.

Step 2: new Object() Constructor

Instead of adding the curly braces, this time we are going to add a new Object() constructor as the value of the variable user:

let user = new Object();

The empty object useris created. Now, we can start pushing values into it:

user.firstName = "Marko"; 
user.lastName = "Markovic";
user.age = 30;

Step 3: Object.create() Function

To understand how the Object.create() function works, we will first create a simple object using the object literal syntax:

let user = {
  firstName: "Marko",
  lastName: "Jovanović",
  age: 30
};

Now we use the Object.create() function to create a new object where the userobject is set as its prototype. Let’s see this in the following example:

user2 = Object.create(user); 
user2.city = "Novi Sad";

Thanks to the JavaScript prototype chain, we can access properties from the userobject through the user2 object:

user2.firstName; // Marko
user2.city; // Novi Sad

Conclusion

JavaScript objects are essential for dealing with data. Unlike Java, where you need to use classes to instantiate objects, JavaScript enables creating, modifying, and extending objects dynamically. Understanding the different ways to create objects and how they function is crucial for effective JavaScript programming.

2
Subscribe to my newsletter

Read articles from Milos Babic directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Milos Babic
Milos Babic

Hey, I'm Milos. I write about code so future me (and maybe you) won’t forget how it works. I am a certified full-stack developer and a tech writer who loves breaking down complex things into something more readable than error logs.