Advertisement
Google Ad Slot: content-top
JS Object
In JavaScript, an object is a collection of key-value pairs. Objects allow you to store and manage data with properties and methods.
Creating an Object:
1.Object Literal Syntax:
Example
let person = {
name: "John",
age: 30,
isStudent: false,
};
console.log(person); // {name:"John",age:30,isStudent:false}
Using the Object Constructor:
Example
const person = new Object();
person.name = "John";
person.age = 30;
console.log(person); // {name:"John",age:30}
Accessing Object Properties
Example
let person = {
name: "John",
age: 30,
isStudent: false,
};
// Dot Notation:
console.log(person.name); // Output: "John"
// Bracket Notation:
console.log(person["age"]); // Output: 30
// Dynamic Property Access:
const property = "isStudent";
console.log(person[property]); // Output: false
Using Methods in Objects:
Objects can also contain functions, which are called methods.
Example
const car = {
make: "Toyota",
model: "Corolla",
year: 2020,
start() {
console.log("The car is starting...");
},
};
console.log(car.make); // Output: "Toyota"
car.start(); // Output: "The car is starting..."
car.color = "Blue"; // Add a new property
console.log(car); // {make: "Toyota", model: "Corolla", year: 2020, start: ƒ, color: "Blue"}