First Thought: An object is a collection of labeled data.
Think of a real-world object, like a person. A person has properties with labels and values:
A JavaScript object is the exact same thing: a container for named values, which we call key-value pairs.
string or Symbol).// This is an object representing a person
let person = {
name: "Alice", // Key is "name", Value is "Alice"
age: 30, // Key is "age", Value is 30
isStudent: true // Key is "isStudent", Value is true
};
A. Creating an Object
The most common and best way to create an object is using the object literal syntax: curly braces {}.
// An empty object
const car = {};
// An object with properties
const user = {
username: "js_dev",
loginCount: 57,
"is-premium-member": true // Keys with special characters must be in quotes
};
B. Accessing (Reading) Properties There are two ways to get a value from an object.
Dot Notation (.): The simplest and most common way. It's clean and easy to read.
console.log(user.username); // "js_dev"
Limitation: Dot notation only works for keys that are valid JavaScript identifiers (no spaces, hyphens, or starting with a number).
Bracket Notation ([]): The more powerful and flexible way. The key inside the brackets is a string.
console.log(user["loginCount"]); // 57
// You MUST use bracket notation for keys with special characters.
console.log(user["is-premium-member"]); // true
CRITICAL USE CASE: Bracket notation allows you to use a variable to determine which property to access.
let propertyToAccess = "username";
console.log(user[propertyToAccess]); // "js_dev" (This is impossible with dot notation)
C. Updating and Adding (Creating) Properties You use the same syntax for both. If the property exists, it's updated. If it doesn't, it's created.