Object Properties in JavaScript

🔍 What Are Object Properties?

In JavaScript, an object property is a key-value pair associated with an object. The key is always a string (or symbol), and the value can be of any data type: string, number, array, function, or another object. 🧩

🛠️ Declaring Object Properties

Object with Properties

const user = {
  name: "Alice",
  age: 25,
  isAdmin: true
};

In this example, name, age, and isAdmin are the object’s properties. 📦

📬 Accessing Object Properties

Dot Notation

Dot Notation

console.log(user.name); // "Alice"
Bracket Notation

Bracket Notation

console.log(user["age"]); // 25

Note

Bracket notation is useful when the property name is dynamic or not a valid identifier (e.g., contains spaces or starts with a number).

🧹 Adding & Updating Properties

Add or Update Properties

user.location = "India";     // Add
user.age = 30;             // Update

🧽 Deleting Properties

Delete Property

delete user.isAdmin;

🔍 Checking for Properties

Check if a Property Exists

"name" in user;         // true
user.hasOwnProperty("age"); // true

🧠 Enumerating Properties

Loop Over Properties

for (let key in user) {
  console.log(key, user[key]);
}

Note

The for...in loop iterates over all enumerable properties, including those inherited from the prototype chain.

🧱 Computed Property Names

You can dynamically compute property names using square brackets during object creation.

Computed Properties

const prop = "score";
const player = {
  [prop]: 100
};

console.log(player.score); // 100

⚠️ Property Key Limitations

Keys are always strings (or symbols), even if you define them as numbers:

Numeric Keys Become Strings

const obj = { 1: "one" };
console.log(obj["1"]); // "one"

📚 Summary

  • Object properties are key-value pairs.
  • Use dot or bracket notation to access them.
  • Add, update, or delete properties anytime.
  • Keys are always strings or symbols under the hood.

📎 More Resources

>>“In JavaScript, everything is an object – or wants to be.” 🧠