beginner

JavaScript Objects

Create and manipulate objects to store structured data in JavaScript.

Objects are the cornerstone of JavaScript. They let you group related data and functionality together using key-value pairs. From simple data records to complex application state, objects are used everywhere. Understanding how to create, access, and modify objects is fundamental to becoming a proficient JavaScript developer.

📚 Concepts & Theory

Creating Objects

const person = {
    name: "Alice",
    age: 25,
    isStudent: true
};

Accessing Properties

// Dot notation
console.log(person.name);  // "Alice"

// Bracket notation
console.log(person["age"]); // 25

// With variables
const key = "name";
console.log(person[key]); // "Alice"

Adding and Modifying Properties

person.email = "[email protected]";  // Add
person.age = 26;  // Modify

Nested Objects

const user = {
    name: "Bob",
    address: {
        city: "New York",
        zip: "10001"
    }
};

console.log(user.address.city); // "New York"

Object Methods

const calculator = {
    value: 0,
    add: function(n) {
        this.value += n;
    }
};

Useful Object Methods

Object.keys(person);    // ["name", "age", "isStudent"]
Object.values(person);  // ["Alice", 25, true]
Object.entries(person); // [["name", "Alice"], ...]

🎯 Your Challenge

Create an object called `book` with properties: title ("JavaScript Guide"), author ("John Doe"), pages (350), and isAvailable (true). Then add a new property `year` with value 2024.

📝 Starter Code

JavaScript
// Create the book object
const book = {
    // Add properties here
};

// Add year property
  • Objects use curly braces {}
  • Properties are key: value pairs
  • Separate properties with commas
  • Use dot notation to add new properties

Solution

JavaScript
const book = {
    title: "JavaScript Guide",
    author: "John Doe",
    pages: 350,
    isAvailable: true
};

book.year = 2024;

Explanation

We create an object using curly braces with key-value pairs. Property names do not need quotes (unless they have special characters). We add the year property using dot notation after the object is created.

⚠️ Common Mistakes to Avoid

  • Using = instead of : for property values
  • Forgetting commas between properties
  • Using quotes around property names unnecessarily
  • Confusing dot and bracket notation

❓ Frequently Asked Questions

Use brackets when the property name is a variable, contains special characters, or is a reserved word. Dot notation is cleaner for simple property names.
Similar but not identical. JSON is a string format for data exchange. JavaScript objects are in-memory data structures. JSON requires quoted keys and cannot contain functions.

🔗 Related Concepts