07

Objects

Chapter 7 • Beginner

35 min

Objects

Objects are collections of key-value pairs where keys are strings (or symbols) and values can be any data type. Objects are fundamental to JavaScript and are used to represent real-world entities.

Creating Objects

Object Literal

javascript.js
let person = {
    name: 'John',
    age: 30,
    city: 'New York',
    isStudent: false
};

Object Constructor

javascript.js
let person = new Object();
person.name = 'John';
person.age = 30;

Accessing Object Properties

Dot Notation

javascript.js
console.log(person.name); // 'John'
console.log(person.age); // 30

Bracket Notation

javascript.js
console.log(person['name']); // 'John'
console.log(person['age']); // 30

Object Methods

Objects can contain functions as properties, which are called methods:

javascript.js
let person = {
    name: 'John',
    age: 30,
    greet: function() {
        return 'Hello, I am ' + this.name;
    },
    // ES6 method shorthand
    introduce() {
        return `Hi, I'm ${this.name} and I'm ${this.age} years old`;
    }
};

Object Manipulation

Adding Properties

javascript.js
person.email = '[email protected]';
person['phone'] = '555-1234';

Modifying Properties

javascript.js
person.age = 31;
person['city'] = 'Boston';

Deleting Properties

javascript.js
delete person.city;

Checking Properties

javascript.js
console.log('name' in person); // true
console.log(person.hasOwnProperty('age')); // true

Object Iteration

for...in Loop

javascript.js
for (let key in person) {
    console.log(key + ': ' + person[key]);
}

Object.keys()

javascript.js
let keys = Object.keys(person);
console.log(keys); // ['name', 'age', 'city']

Object.values()

javascript.js
let values = Object.values(person);
console.log(values); // ['John', 30, 'New York']

Object.entries()

javascript.js
let entries = Object.entries(person);
console.log(entries); // [['name', 'John'], ['age', 30], ['city', 'New York']]

Hands-on Examples

Object Basics

let student = {
    name: 'Alice',
    age: 20,
    grade: 'A',
    subjects: ['Math', 'Science', 'English']
};

console.log('Name:', student.name);
console.log('Age:', student['age']);
console.log('Grade:', student.grade);
console.log('Subjects:', student.subjects);

Objects store data as key-value pairs. You can access properties using dot notation or bracket notation.