Object Literals

Objects are collections of key-value pairs, where the keys are strings (or symbols), and the values can be of any data type, including other objects or functions.

const person = {
name: "John Doe",
age: 30,
isStudent: false,
greet: function() {
console.log("Hello!");
}
};

Object Properties and Methods

You can access object properties using dot notation or bracket notation:

console.log(person.name); // "John Doe"
console.log(person["age"]); // 30
person.greet(); // "Hello!"

Constructor Functions and Prototypes

Constructor functions are used to create objects with similar properties and methods. They are defined using a function and invoked with the new keyword.

function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(Hello, my name is ${this.name});
};
const john = new Person("John", 30);
john.greet(); // "Hello, my name is John"

Classes (introduced in ES6)

ES6 introduced a new syntax for creating objects using classes, which is syntactically similar to object-oriented programming in other languages.

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(Hello, my name is ${this.name});
}
}
const john = new Person("John", 30);
john.greet(); // "Hello, my name is John"

 

Object Destructuring

Object destructuring allows you to extract properties from an object and assign them to variables in a concise way.

const person = {
name: "John Doe",
age: 30,
city: "New York"
};
const { name, age } = person;
console.log(name); // "John Doe"
console.log(age); // 30

 

In the next chapter, we'll explore DOM manipulation, which allows you to interact with and modify the structure and content of web pages using JavaScript.