Skip to main content

JavaScript Objects Basics

Introduction

Objects are one of the core data structures in JavaScript. Unlike primitive data types (numbers, strings, booleans), objects allow you to store collections of data with key-value pairs. Think of objects as containers that can hold multiple related values, similar to how a physical container might hold different items.

In this tutorial, you'll learn:

  • What JavaScript objects are and why they're important
  • Different ways to create objects
  • How to access, modify, and delete object properties
  • Common operations and methods for working with objects

What is a JavaScript Object?

In JavaScript, an object is an unordered collection of key-value pairs. Each key (also called a property) has an associated value, which can be any JavaScript data type including other objects, arrays, or functions.

Objects are represented using curly braces {}, with properties and their values written as key: value pairs separated by commas.

Creating Objects

Object Literal Notation

The most common way to create an object is using the object literal notation:

javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
isEmployed: true
};

console.log(person);

Output:

{firstName: "John", lastName: "Doe", age: 30, isEmployed: true}

Using the Object Constructor

You can also create objects using the Object() constructor:

javascript
const car = new Object();
car.make = "Toyota";
car.model = "Corolla";
car.year = 2022;

console.log(car);

Output:

{make: "Toyota", model: "Corolla", year: 2022}

Accessing Object Properties

There are two main ways to access object properties:

Dot Notation

javascript
const person = {
firstName: "John",
lastName: "Doe"
};

console.log(person.firstName); // Output: John
console.log(person.lastName); // Output: Doe

Bracket Notation

javascript
const person = {
firstName: "John",
lastName: "Doe"
};

console.log(person["firstName"]); // Output: John
console.log(person["lastName"]); // Output: Doe

Bracket notation is particularly useful when:

  • The property name contains spaces or special characters
  • The property name is stored in a variable
  • You need to access properties dynamically
javascript
const person = {
"first name": "John",
"last name": "Doe"
};

console.log(person["first name"]); // Output: John

const propertyName = "last name";
console.log(person[propertyName]); // Output: Doe

Modifying Object Properties

Objects are mutable, meaning you can change their properties after creation:

javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};

// Modifying existing properties
person.age = 31;
person["lastName"] = "Smith";

// Adding new properties
person.email = "[email protected]";
person["phone"] = "555-123-4567";

console.log(person);

Output:

{
firstName: "John",
lastName: "Smith",
age: 31,
email: "[email protected]",
phone: "555-123-4567"
}

Deleting Properties

You can remove properties using the delete operator:

javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
email: "[email protected]"
};

delete person.email;
console.log(person); // {firstName: "John", lastName: "Doe", age: 30}

// Check if a property exists
console.log("email" in person); // Output: false
console.log("firstName" in person); // Output: true

Objects with Methods

Objects can also contain functions as properties, which are called methods:

javascript
const calculator = {
num1: 0,
num2: 0,
sum: function() {
return this.num1 + this.num2;
},
multiply: function() {
return this.num1 * this.num2;
}
};

calculator.num1 = 5;
calculator.num2 = 3;

console.log(calculator.sum()); // Output: 8
console.log(calculator.multiply()); // Output: 15

A more concise way to define methods in object literals (ES6 syntax):

javascript
const calculator = {
num1: 0,
num2: 0,
sum() {
return this.num1 + this.num2;
},
multiply() {
return this.num1 * this.num2;
}
};

Nested Objects

Objects can contain other objects as properties:

javascript
const person = {
name: {
first: "John",
last: "Doe"
},
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
zip: "12345"
}
};

// Accessing nested properties
console.log(person.name.first); // Output: John
console.log(person.address.city); // Output: Anytown

Object Methods and Properties

JavaScript provides several built-in methods and properties to work with objects:

Object.keys()

Returns an array of a given object's own property names:

javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};

const keys = Object.keys(person);
console.log(keys); // Output: ["firstName", "lastName", "age"]

Object.values()

Returns an array of a given object's own property values:

javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};

const values = Object.values(person);
console.log(values); // Output: ["John", "Doe", 30]

Object.entries()

Returns an array of a given object's own [key, value] pairs:

javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};

const entries = Object.entries(person);
console.log(entries);
// Output: [["firstName", "John"], ["lastName", "Doe"], ["age", 30]]

Real-World Example: User Profile

Let's create a more complex object representing a user profile for a social media application:

javascript
const userProfile = {
userId: "user123",
personalInfo: {
firstName: "Jane",
lastName: "Smith",
dateOfBirth: "1992-04-15",
email: "[email protected]",
phone: "555-987-6543"
},
address: {
street: "456 Oak Avenue",
city: "San Francisco",
state: "CA",
zip: "94107",
country: "USA"
},
preferences: {
theme: "dark",
notifications: true,
privacy: "friends-only"
},
friends: ["user456", "user789", "user101"],
posts: [
{
id: "post1",
content: "Hello world!",
timestamp: "2023-06-15T14:30:00Z",
likes: 15
},
{
id: "post2",
content: "Learning JavaScript objects!",
timestamp: "2023-06-16T10:15:00Z",
likes: 42
}
],
isActive: true,
lastLogin: "2023-06-17T08:45:00Z",

// Methods
fullName() {
return `${this.personalInfo.firstName} ${this.personalInfo.lastName}`;
},

addFriend(friendId) {
this.friends.push(friendId);
return this.friends.length;
},

createPost(content) {
const newPost = {
id: `post${this.posts.length + 1}`,
content: content,
timestamp: new Date().toISOString(),
likes: 0
};
this.posts.push(newPost);
return newPost;
}
};

// Using the user profile object
console.log(userProfile.fullName()); // Output: Jane Smith

userProfile.addFriend("user202");
console.log(userProfile.friends); // Output: ["user456", "user789", "user101", "user202"]

const newPost = userProfile.createPost("Objects are awesome!");
console.log(newPost); // Output: A new post object with 0 likes

This example demonstrates how objects can model complex real-world entities with both data and behavior.

Summary

In this tutorial, you've learned the basics of JavaScript objects:

  • Objects are collections of key-value pairs
  • Creating objects using literal notation and constructors
  • Accessing, modifying, and deleting object properties
  • Working with methods inside objects
  • Handling nested objects
  • Using built-in object methods like Object.keys(), Object.values(), and Object.entries()

JavaScript objects are fundamental to the language and form the basis of more advanced concepts like prototypes, classes, and object-oriented programming in JavaScript.

Exercises

  1. Create an object to represent a book with properties for title, author, publication year, and genre.
  2. Add a method to the book object that returns a string describing the book.
  3. Create a nested object representing a shopping cart with items, quantities, and prices.
  4. Write a function that takes an object and returns the number of properties it has.
  5. Create an address book object that can add, remove, and look up contacts.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)