JavaScript Objects
JavaScript Objects
1. What is an Object?
An object in JavaScript is a collection of key-value pairs where the keys
(properties) are strings (or Symbols), and the values can be any data type.
let person = {
name: "John",
age: 30,
isEmployed: true
};
2. Creating Objects
Using Object Literals (Most Common)
let car = {
brand: "Toyota",
model: "Camry",
year: 2022
};
Using the new Object() Constructor
let parent = {
greet: function() {
console.log("Hello!");
}
};
let child = Object.create(parent);
child.name = "Kid";
console.log(child.name); // Kid
child.greet(); // Hello!
3. Accessing and Modifying Properties
Dot Notation (Recommended)
console.log(person.name); // John
person.age = 31;
Bracket Notation (Useful for dynamic keys)
console.log(person["name"]); // John
let key = "age";
console.log(person[key]); // 31
Adding and Deleting Properties
let student = {
name: "Emma",
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
student.greet(); // Hello, my name is Emma
📝 this refers to the current object.