Javascript Objects
What is Objects in JS:
Objects are used to group related data and functionality together.
Object Literals:
Object literals is a one-liner convenient way to create object which we can accomplish using a single line.
// Object literal
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function() {
console.log("Hello, " + this.firstName + "!");
}
};
// Accessing properties
console.log(person.firstName); // Output: "John"
// Accessing methods
person.greet(); // Output: "Hello, John!"
In this example, person is an object with properties (firstName, lastName, age) and a method (greet).
Object Constructors:
Object constructors allows instantiation of objects that have many similar structures.
Constructors are functions that are used just like any of the other normal functions with the new keyword.
// Object constructor
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.greet = function() {
console.log("Hello, " + this.firstName + "!");
};
}
// Creating objects using the constructor
let person1 = new Person("John", "Doe", 30);
let person2 = new Person("Jane", "Doe", 25);
// Accessing properties
console.log(person1.firstName); // Output: "John"
console.log(person2.age); // Output: 25
// Accessing methods
person1.greet(); // Output: "Hello, John!"
person2.greet(); // Output: "Hello, Jane!"
In this example, Person is an object constructor, and person1 and person2 are instances created using this constructor.
Accessing Properties and Methods:
You can access properties and methods of objects using dot notation.
let car = {
brand: "Toyota",
model: "Camry",
start: function() {
console.log("Engine started!");
}
};
// Accessing properties
console.log(car.brand); // Output: "Toyota"
// Accessing methods
car.start(); // Output: "Engine started!"
Adding and Modifying Properties:
You can add or modify properties of objects dynamically.
let person = {
firstName: "John",
lastName: "Doe"
};
// Adding a new property
person.age = 30;
// Modifying an existing property
person.lastName = "Smith";
console.log(person); // Output: { firstName: "John", lastName: "Smith", age: 30 }