Objects in JS: The Beginner’s Guide

JavaScript objects are essentially associative arrays with some extra features​. They store properties (key-value pairs) where each key is a name (usually a string or symbol) that maps to a value (which can be any data type)​. In other words, each property is like a named slot holding a value. Because objects map names to values, they’re often described as associative array. Key-Value Pairs (Properties) Each property in an object has a key and a value. Keys must be strings (or symbols) and values can be anything (number, string, another object, etc.). For example, a mobile data plan could be represented as: const plan = { name: "Basic 1GB", price: 10, validity: 30 }; Here plan has three properties: "name" (value "Basic 1GB"), "price" (value 10), and "validity" (value 30). The keys (name, price, validity) are strings, and the values are a mix of string and number. You can have as many properties as needed, and values can even be objects or functions. This object literal { ... } notation creates a new plain object with the given key-value pairs​. Accessing Properties You can access an object’s properties in two main ways: 1. Dot notation: obj.key – this is simple and readable. console.log(plan.name); // "Basic 1GB" 2. Bracket notation: obj["key"] – this looks like array syntax and uses a string in quotes. console.log(plan["price"]); // 10 Both lines above read the same values. Bracket notation is useful when the key name is dynamic or not a valid identifier. For example: let field = "validity"; console.log(plan[field]); // 30 Here field is a variable holding the key name. Bracket notation (plan[field]) allows using variables or strings computed at runtime​. (You must use quotes inside brackets when writing the key literally, like plan["name"].) Additional Operations JavaScript provides some extra operators for objects: Delete a property: delete obj.key – removes that key from the object. Check if key exists: "key" in obj – returns true if the object has that property (even if its value is undefined). Iterate keys: for (let key in obj) { … } – loops over all enumerable keys in the object. const course = { courseName: "JS 101", duration: "4 weeks", instructor: "Alice" }; delete course.instructor; // removes the instructor property console.log("instructor" in course); // false for (let key in course) { console.log(key, course[key]); // logs remaining keys and values } The delete operator removes a property​. The in operator tests for a key’s presence​. And the for...in loop iterates over each key in turn​. These tools let you manage and inspect object properties at runtime. Plain vs Specialized Objects What we’ve described so far are plain objects (created with {}). JavaScript has many other built-in objects that extend this concept​. For example, an Array is a special object used for ordered lists (with numeric indices), Date is an object for handling dates and times, and Error is an object for error information​. Arrays and Dates are not separate “types” in the language; they are just objects with extra functionality. In code, you create them with their respective syntax (e.g. [] for arrays or new Date() for a date), but they still use key-value storage under the hood. Examples Here are some real-world examples of objects in different contexts: 1. General const plan = { name: "Basic 1GB", price: 10, validity: 30 }; This plan object stores details of a data package. We can access plan.name, plan.price, and plan.validity to get each detail. 2. Multiword Property Name const ticket = { event: "Pet Show", seat: "A12", price: 50, "booking time": "7:00 PM" // multiword property name must be quoted }; // Accessing multiword property console.log(ticket["booking time"]); // "7:00 PM" A ticket object might hold the event name, seat number, and price. We can use ticket.seat or ticket["price"] to access these values. But, Multiword property names must be in quotes when defining them. You can’t use dot notation to access them (ticket.booking time would cause a syntax error). Instead, use bracket notation: ticket["booking time"] 3. Property Name with Special Characters const payment = { id: "TX123", amount: 100, "payment-status": "Pending" }; console.log(payment["payment-status"]); // ✅ "Pending" // console.log(payment.payment-status); // ❌ Unexpected token '-' Any special character (like -, space, etc.) requires quotes and bracket notation. 4. Property Name Starts with a Number const course = { "101": "Intro to JavaScript", duration: "4 weeks" }; console.log(course["101"]); // ✅ "Intro to JavaScript" // console.log(course.101); // ❌ SyntaxError Property names that start with digits must also be accessed using bracket notation. 5. Access with a Variable Key const student = { name: "Ayesha", grade: "A+" }; let ke

May 4, 2025 - 07:42
 0
Objects in JS: The Beginner’s Guide

JavaScript objects are essentially associative arrays with some extra features​. They store properties (key-value pairs) where each key is a name (usually a string or symbol) that maps to a value (which can be any data type)​. In other words, each property is like a named slot holding a value. Because objects map names to values, they’re often described as associative array.

Key-Value Pairs (Properties)

Each property in an object has a key and a value. Keys must be strings (or symbols) and values can be anything (number, string, another object, etc.). For example, a mobile data plan could be represented as:

const plan = {
  name: "Basic 1GB",
  price: 10,
  validity: 30
};

Here plan has three properties: "name" (value "Basic 1GB"), "price" (value 10), and "validity" (value 30). The keys (name, price, validity) are strings, and the values are a mix of string and number. You can have as many properties as needed, and values can even be objects or functions. This object literal { ... } notation creates a new plain object with the given key-value pairs​.

Accessing Properties

You can access an object’s properties in two main ways:

1. Dot notation:
obj.key – this is simple and readable.

console.log(plan.name);    // "Basic 1GB"

2. Bracket notation:
obj["key"] – this looks like array syntax and uses a string in quotes.

console.log(plan["price"]); // 10

Both lines above read the same values. Bracket notation is useful when the key name is dynamic or not a valid identifier.
For example:

let field = "validity";
console.log(plan[field]); // 30

Here field is a variable holding the key name. Bracket notation (plan[field]) allows using variables or strings computed at runtime​. (You must use quotes inside brackets when writing the key literally, like plan["name"].)

Additional Operations

JavaScript provides some extra operators for objects:
Delete a property: delete obj.key – removes that key from the object.
Check if key exists: "key" in obj – returns true if the object has that property (even if its value is undefined).
Iterate keys: for (let key in obj) { … } – loops over all enumerable keys in the object.

const course = { 
    courseName: "JS 101", 
    duration: "4 weeks", 
    instructor: "Alice" 
};
delete course.instructor;             // removes the instructor property
console.log("instructor" in course);  // false
for (let key in course) {
  console.log(key, course[key]);      // logs remaining keys and values
}

The delete operator removes a property​. The in operator tests for a key’s presence​. And the for...in loop iterates over each key in turn​. These tools let you manage and inspect object properties at runtime.

Plain vs Specialized Objects

What we’ve described so far are plain objects (created with {}). JavaScript has many other built-in objects that extend this concept​. For example, an Array is a special object used for ordered lists (with numeric indices), Date is an object for handling dates and times, and Error is an object for error information​. Arrays and Dates are not separate “types” in the language; they are just objects with extra functionality. In code, you create them with their respective syntax (e.g. [] for arrays or new Date() for a date), but they still use key-value storage under the hood.
Examples
Here are some real-world examples of objects in different contexts:

1. General

const plan = {
  name: "Basic 1GB",
  price: 10,
  validity: 30
};

This plan object stores details of a data package. We can access plan.name, plan.price, and plan.validity to get each detail.

2. Multiword Property Name

const ticket = {
  event: "Pet Show",
  seat: "A12",
  price: 50,
  "booking time": "7:00 PM" // multiword property name must be quoted
};

// Accessing multiword property
console.log(ticket["booking time"]); // "7:00 PM"

A ticket object might hold the event name, seat number, and price. We can use ticket.seat or ticket["price"] to access these values. But, Multiword property names must be in quotes when defining them.
You can’t use dot notation to access them (ticket.booking time would cause a syntax error).

Instead, use bracket notation: ticket["booking time"]

3. Property Name with Special Characters

const payment = {
  id: "TX123",
  amount: 100,
  "payment-status": "Pending"
};

console.log(payment["payment-status"]); // ✅ "Pending"
// console.log(payment.payment-status); // ❌ Unexpected token '-'

Any special character (like -, space, etc.) requires quotes and bracket notation.

4. Property Name Starts with a Number

const course = {
  "101": "Intro to JavaScript",
  duration: "4 weeks"
};
console.log(course["101"]); // ✅ "Intro to JavaScript"
// console.log(course.101); // ❌ SyntaxError

Property names that start with digits must also be accessed using bracket notation.

5. Access with a Variable Key

const student = {
  name: "Ayesha",
  grade: "A+"
};

let key = "grade";
console.log(student[key]); // ✅ "A+"

Use bracket notation when the property name is stored in a variable.

6. Using Symbols as Property Keys

const uniqueKey = Symbol("id");
const user = {
  name: "Rahim",

};
console.log(user[uniqueKey]); // ✅ 12345

Symbol keys must be accessed with bracket notation; dot notation won’t work.

7. Built-in Objects Types

let arr = [1, 2, 3];         // Array – ordered collection
let now = new Date();        // Date – current date and time
let err = new Error("Oops"); // Error – represents runtime errors

These are all extended forms of "object"

Summary

This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies.