JavaScript Objects

Working with Objects

Objects are collections of key-value pairs. They allow you to group related data and functions together.

Objects are one of the most important data types in JavaScript and are used everywhere.

// Creating Objects
const person = {
  name: 'John',
  age: 30,
  city: 'New York',
  isStudent: false
};

// Accessing Properties
console.log(person.name);      // Dot notation
console.log(person['age']);    // Bracket notation

// Modifying Properties
person.age = 31;
person['city'] = 'Boston';

// Adding Properties
person.email = 'john@example.com';

// Object Methods
const calculator = {
  value: 0,
  add: function(num) {
    this.value += num;
    return this.value;
  },
  reset: function() {
    this.value = 0;
  }
};

calculator.add(10);  // 10
calculator.add(5);   // 15

// Object Destructuring
const { name, age } = person;
console.log(name, age);
  • Objects store key-value pairs
  • Access with dot notation (obj.key)
  • Access with bracket notation (obj['key'])
  • Can contain any data type
  • Methods are functions inside objects
  • this keyword refers to the object
  • Destructuring extracts values easily

Try Objects

<div class="object-demo">
  <h3>Create Your Profile</h3>
  <input type="text" id="userName" placeholder="Name">
  <input type="number" id="userAge" placeholder="Age">
  <input type="text" id="userCity" placeholder="City">
  <button onclick="createProfile()">Create Profile</button>
  <div id="profileOutput"></div>
</div>

Note: Objects are fundamental to JavaScript. Almost everything in JavaScript is an object!