Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Object Properties

Object properties store values under keys, and you can access them using dot or bracket notation.

Understanding property access is essential for working with real data structures.

Why We Need It

Most data in JavaScript is represented as objects with properties.

Knowing how to access and update properties prevents common bugs.

Syntax

obj.key
obj['key']
delete obj.key

Basic Example

1. Dot vs bracket

const user = { name: "Ava", "role type": "admin" };

console.log(user.name);
console.log(user["role type"]);

Dot for simple keys, bracket for special keys.

Real World Example

2. Dynamic key

const key = "email";
const user = {};
user[key] = "a@example.com";

console.log(user.email);

Use bracket notation for dynamic keys.

Multiple Use Cases

Access Properties

Use dot notation for static keys and bracket notation for dynamic keys.

Bracket notation also allows keys with spaces or special characters.

Add and Update

You can add new properties or update existing ones with simple assignment.

Objects are mutable by default.

Delete and Check

Use delete to remove a property and in or hasOwn to check existence.

Prefer Object.hasOwn for own properties only.

More Examples

3. Update

const user = { name: "Ava" };
user.name = "Riya";

console.log(user);

Assignment updates properties.

4. Delete

const user = { name: "Ava", age: 22 };
delete user.age;

console.log(user);

delete removes a property.

Comparison

Without

const value = obj['dynamicKey'];

With

const value = obj[dynamicKey];

Common Mistakes and Fixes

Using dot for dynamic keys

Use bracket notation for variables as keys.

Deleting in performance-critical loops

Prefer creating new objects when possible.

Assuming property exists

Check with in or Object.hasOwn before access.

Interview Questions

Dot vs bracket access?

Dot for static keys, bracket for dynamic or special keys.

How do you delete a property?

Use delete obj.key.

How do you check existence?

Use in or Object.hasOwn.

Practice Problem

Practice: Add a property called role to a user object and log it.

const user = { name: "Ava" };
// TODO: add role

One Possible Solution

const user = { name: "Ava" };
user.role = "admin";
console.log(user.role);

Frequently Asked Questions

When should I use bracket notation?

When the key is dynamic or has special characters.

How do I check if a property exists?

Use key in obj or Object.hasOwn(obj, key).

Does delete remove nested properties?

It removes only the property you target.

Try It Yourself

Try accessing properties with dot and bracket notation.