Object in JavaScript is a collection of key-value
pairs. It is used to store multiple values in a structured manner.
Syntax:
let objectName = {
key1: value1,
key2: value2,
key3: value3
};
- Key → Property name (string)
- Value → Can be string, number, boolean, array, function, or any other object.
Creating an Object
Using Object Literal (Most Common)
let person = {
name: "John",
age: 30,
city: "New York"
};
console.log(person); // { name: "John", age: 30, city: "New York" }
Accessing Object Properties
- Using Dot Notation (
.
)
console.log(person.name); // "John"
console.log(person.age); // 30
- Using Bracket Notation (
[]
)
console.log(person["name"]); // "John"
console.log(person["age"]); // 30
Use bracket notation when property names have spaces or special characters
let obj = { "first name": "John" };
console.log(obj["first name"]); // "John"
Adding & Updating Properties
Adding a New Property
person.country = "USA";
console.log(person.country); // "USA"
Updating an Existing Property
person.age = 35;
console.log(person.age); // 35
Deleting a Property
delete person.city;
console.log(person.city); // undefined
Checking if a Property Exists
Using in
Operator
console.log("age" in person); // true
console.log("city" in person); // false
Using hasOwnProperty()
console.log(person.hasOwnProperty("name")); // true
console.log(person.hasOwnProperty("city")); // false
Looping Through an Object
Using for...in
loop
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output:
name: John
age: 35
country: USA
Nested Objects
Objects can also contain other objects.
let student = {
name: "Alice",
marks: {
math: 90,
science: 85
}
};
console.log(student.marks.math); // 90
console.log(student["marks"]["science"]); // 85
Object Methods (Functions Inside Objects)
An object method is a function that is stored inside an object.
let car = {
brand: "Toyota",
model: "Corolla",
start: function() {
return "Car started";
}
};
console.log(car.start()); // "Car started"
this
Keyword in Objects
this
refers to the current object.
let user = {
name: "Alex",
greet: function() {
return "Hello, " + this.name;
}
};
console.log(user.greet()); // "Hello, Alex"
Creating Objects Using new Object()
let car = new Object();
car.brand = "Ford";
car.model = "Mustang";
console.log(car.brand); // "Ford"
Summary
- Objects store data as key-value pairs.
- Methods are functions inside the object.
- Use the dot (.) or bracket ([]) notation to access properties.
- Use a for...in loop to iterate over the object.
- Use this to refer to the current object.
I hope you understand clearly the javascript objects.
Thanks.
Also, read: JavaScript Loops Explanation
Leave Comment