Skip to main content
Practice

Object

An object is a collection of data represented as key-value pairs.

Here, the key is a string, and the value can be various data types (primitives, objects, functions, etc.).


Creating an object

In JavaScript, an object is created using curly braces { }.

You can represent your wallet as an object like this:

Creating a Wallet Object
let wallet = {
cash: 100,
card: 'Visa',
driverLicense: true,
};

cash, card, and driverLicense are properties of the object, and 100, 'Visa', true are the values of these properties.

Properties and values are connected with a colon (:), and each property is separated by a comma (,).


Accessing information from objects

There are two ways to retrieve information from an object.


Using the dot (.) notation

This is the most common method used to access the properties of an object.

Accessing Object Information with Dot Notation
let myMoney = wallet.cash; // 100

Using square brackets ([]) and keys

This method is useful when the key is given as a variable or contains spaces or special characters.

Accessing Object Information with Square Brackets
let myCard = wallet['card']; // 'Visa'

Modifying and adding information to objects

To modify or add information to an object, you can use both dot (.) notation and square brackets ([]).

Modifying and Adding Information to Objects
// Adding a new property
wallet['picture'] = 'family';

// Modifying an existing property's value
wallet.cash = 200;

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.