JAVASCRIPT PROGRAMMING:Objects

Mastering objects concepts and implementation.

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

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

Object Constructor

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

Accessing Object Properties

Dot Notation

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

Bracket Notation

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

Object Methods

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

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

person.email = 'john@example.com';
person['phone'] = '555-1234';

Modifying Properties

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

Deleting Properties

delete person.city;

Checking Properties

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

Object Iteration

for...in Loop

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

Object.keys()

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

Object.values()

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

Object.entries()

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.