Skip to main content

Creating and Accessing Objects

Objects are an integral part of JavaScript and they allow us to create complex structures and data types. An object is a standalone entity that holds a collection of properties. Each property is a key-value pair, where the key is a string (or symbol) and the value can be anything.

Creating an Object

There are several ways to create an object in JavaScript. The simplest way is to use the object literal syntax.

let car = {};

In the above example, we have created an empty object named 'car'. We can also create an object with some initial properties.

let car = {
brand: "Toyota",
model: "Corolla",
year: 2005
};

In this case, we have created an object with three properties: brand, model, and year. The names of the properties are the keys, and the corresponding values are the values of these properties.

Accessing Object Properties

Once an object is created, we can access its properties using the dot notation or the bracket notation.

Dot Notation

The dot notation is straightforward and easy to read.

console.log(car.brand); // Toyota
console.log(car.model); // Corolla
console.log(car.year); // 2005

Bracket Notation

The bracket notation is more versatile because it allows us to access properties using variables or strings that may not be valid identifiers.

console.log(car['brand']); // Toyota
console.log(car['model']); // Corolla
console.log(car['year']); // 2005

Bracket notation is especially useful when the name of the property is stored in a variable.

let property = 'brand';
console.log(car[property]); // Toyota

Adding and Modifying Properties

You can add new properties or modify existing ones using the dot notation or the bracket notation.

// Adding a new property
car.color = 'red';
console.log(car.color); // red

// Modifying an existing property
car.year = 2010;
console.log(car.year); // 2010

In conclusion, objects in JavaScript are key-value pairs that provide a flexible and intuitive way to organize and access data. They are extremely useful for creating complex data structures and are one of the fundamental building blocks of JavaScript. Practice creating, accessing, and manipulating objects to get a good grasp of this concept.