JavaScript objects let you group related data and behavior together. Properties store data about the object, methods define what the object can do, and constructors/classes help you create many similar objects easily.
? Properties = Data ⚙️ Methods = Actions ?️ Constructors = Object Factory
this refers to the current object inside a method or constructor.An object literal is written with curly braces {}. Each property is a key: value pair. You can access properties using dot notation (obj.key) or bracket notation (obj["key"]).
thisWhen a function is stored as a property, it is called a method. Inside methods, this points to the object that owns the method (when called as obj.method()).
You can loop over properties using for...in or convert the entire object into a JSON string using JSON.stringify() for easy logging or sending over a network.
Constructor functions (pre-ES6) and class syntax (ES6+) provide patterns to create many objects with the same structure. Use the new keyword to create instances.
// Defining an object with properties
const car = {
make: "Toyota",
model: "Corolla",
year: 2020
};
// Accessing properties
console.log(car.make); // Output: Toyota
console.log(car["model"]); // Output: Corolla
// Adding or modifying properties
car.color = "Blue";
car.year = 2021;
console.log(car.color); // Output: Blue
console.log(car.year); // Output: 2021
const person = {
firstName: "Jane",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // Output: Jane Doe
// ES6 shorthand for methods
const person2 = {
firstName: "John",
lastName: "Smith",
fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person2.fullName()); // Output: John Smith
// Loop through properties using for...in
for (let key in car) {
console.log(key + ": " + car[key]);
}
/*
Output:
make: Toyota
model: Corolla
year: 2021
color: Blue
*/
// Convert object to JSON string
const jsonStr = JSON.stringify(car);
console.log(jsonStr);
// Example output:
// {"make":"Toyota","model":"Corolla","year":2021,"color":"Blue"}
// Parse JSON string back to object
const newCar = JSON.parse(jsonStr);
console.log(newCar.make); // Output: Toyota
// Constructor function example
function Animal(type, sound) {
this.type = type;
this.sound = sound;
this.speak = function() {
return `${this.type} says ${this.sound}`;
};
}
// Create new instances
const dog = new Animal("Dog", "Woof");
const cat = new Animal("Cat", "Meow");
console.log(dog.speak()); // Output: Dog says Woof
console.log(cat.speak()); // Output: Cat says Meow
// ES6 Class syntax (modern way)
class AnimalClass {
constructor(type, sound) {
this.type = type;
this.sound = sound;
}
speak() {
return `${this.type} says ${this.sound}`;
}
}
const bird = new AnimalClass("Bird", "Chirp");
console.log(bird.speak()); // Output: Bird says Chirp
car object stores details like make, model, year, and color. You can read and update these using dot or bracket notation.person and person2 objects both define a fullName() method that uses this.firstName and this.lastName.for...in loop prints every property name and value of car.JSON.stringify(car) turns the object into a string for logging or sending over a network, and JSON.parse() reverses it back into an object.Animal and class AnimalClass both define a pattern for creating objects with type, sound, and a speak() method.User, Post).Click the button to display information from a JavaScript object:
Click the button to see the car details here.
for...in carefully; it iterates over all enumerable properties, including inherited ones.new keyword with constructor functions to ensure this refers to the new object.this, since arrow functions do not have their own this.book with properties: title, author, and pages."Title by Author (X pages)").for...in loop to print all properties and values of the book object.book objects.isLongBook() that returns true if pages > 300.