JavaScript Objects hold values as key and value pairs, and they help you store and access data.
Table of Content
- Understand the JavaScript Objects
- Create JavaScript Objects
- Access Object Properties
- Update and Add Properties
- Delete Properties in Objects
- Object Methods and Functions
- How to Loop Through Objects in JavaScript
- Nested Objects and Arrays
- Destruct an Object in JavaScript
- Examples of Objects in JavaScript
- Wrapping Up
- FAQs
Understand the JavaScript Objects
A JavaScript Object is a group of key and value pairs that act like a small data holder. Each key points to a value that can be any type.
You use curly braces to make an Object, and each key links to a value. A colon separates them, and you must use commas between pairs.
Here is the syntax:
var objectData = {
value1: "This is value 1",
value2: "This is value 2"
};
The browser treats each key as a way to reach its value. Once you call the key, you get the stored value linked to it.
Here is a quick example:
let user = { name: "Ali", age: 25 };
console.log(user.name);
The code above makes an Object named user
. The key name
points to "Ali"
and age
points to 25
. The console shows "Ali"
.
Create JavaScript Objects
You can make a new Object with curly braces or with the new Object()
way. Both ways give you the same result in the end.
Here is an example:
let car = { brand: "Toyota", year: 2020 };
console.log(car.brand);
Here the Object car
has two keys. One key is brand
with value "Toyota"
, and the other is year
with value 2020
.
For another example:
let person = new Object();
person.name = "Sara";
person.age = 22;
console.log(person.age);
This time you use new Object()
and then set keys one by one. The value 22
shows when you print person.age
.
Access Object Properties
You can reach values inside an Object by dot notation or bracket notation. Both ways give you the same data when you use the right key.
Here is an example:
let book = { title: "Math", pages: 300 };
console.log(book.title);
Dot notation prints "Math"
because the key title
links to that value.
Example 2:
let book = { title: "Math", pages: 300 };
console.log(book["pages"]);
Bracket notation prints 300
because the key inside brackets matches the stored key name.
Update and Add Properties
You can change the values of keys inside Objects or add new keys if needed. JavaScript lets you add new keys at any time.
Example 1:
let phone = { brand: "Nokia", price: 200 };
phone.price = 150;
console.log(phone.price);
The value of price
changes from 200
to 150
when you assign the new value.
Example 2:
let phone = { brand: "Nokia", price: 200 };
phone.color = "Black";
console.log(phone.color);
The code adds a new key color
with value "Black"
without removing any old key.
Delete Properties in Objects
You can remove keys from an Object by using the delete
keyword before the key name.
For example:
let city = { name: "Riyadh", population: 7000000 };
delete city.population;
console.log(city);
The Object keeps name
but no longer has population
after you delete it.
Here is another exmaple:
let city = { name: "Riyadh", country: "Saudi" };
delete city.name;
console.log(city.country);
Here name
is gone, but the key country
still exists and shows "Saudi"
.
Object Methods and Functions
A method is a function stored as a key value inside an Object. You call it like any function, but it lives inside that Object.
For example:
let student = { name: "Omar", greet: function() { return "Hello"; } };
console.log(student.greet());
The Object holds a method named greet
that runs and prints "Hello"
.
For another example:
let calc = { add: function(x, y) { return x + y; } };
console.log(calc.add(4, 6));
Here the Object calc
has a method add
which gives back the sum of two numbers.
How to Loop Through Objects in JavaScript
You can use for...in
to go through each key inside an Object. Each step gives you one key, and you can use it to reach its value.
Example 1:
let fruit = { name: "Apple", color: "Red" };
for (let key in fruit) {
console.log(key + ": " + fruit[key]);
}
The loop runs two times. First it shows "name: Apple"
then "color: Red"
.
Example 2:
let scores = { math: 90, science: 85 };
for (let key in scores) {
console.log(scores[key]);
}
This loop prints 90
and 85
because it goes through each key in the Object.
Nested Objects and Arrays
An Object can hold another Object or even an Array inside it. This makes your data structure more deep and useful.
For example:
let user = { name: "Aisha", address: { city: "Jeddah", zip: 12345 } };
console.log(user.address.city);
The key address
holds another Object. You can reach its city
key with dot notation.
Example 2:
let data = { users: ["Ali", "Sara", "Huda"] };
console.log(data.users[1]);
The value is an Array. You can reach "Sara"
because it is at index 1
in the Array.
Destruct an Object in JavaScript
Destruct means you take values from an Object and save them into new variables.
For example:
let person = { name: "Khalid", age: 30 };
let { name, age } = person;
console.log(name);
The code takes the keys name
and age
and saves them as new variables with the same names.
Here is another example:
let laptop = { brand: "Dell", price: 800 };
let { price } = laptop;
console.log(price);
Here only price
comes out from the Object, so the console shows 800
.
Examples of Objects in JavaScript
Student Scores:
let student = { name: "Omar", scores: { math: 85, science: 90 } };
console.log(student.scores.science);
This Object has another Object inside it that holds subject scores. When you call student.scores.science
, the console shows 90
.
Shop Items Array:
let shop = { items: ["Milk", "Bread", "Rice"], owner: "Yusuf" };
console.log(shop.items[2]);
The Object shop
stores an Array inside the key items
. The console shows "Rice"
because it sits at index 2
.
Method Inside Object:
let person = { name: "Fatima", greet: function() { return "Hi " + this.name; } };
console.log(person.greet());
This Object has a method greet
that uses this.name
. The console prints "Hi Fatima"
when you call it.
Use of Destruct:
let car = { brand: "Honda", year: 2021, price: 20000 };
let { brand, price } = car;
console.log(brand + " costs " + price);
This code pulls out two keys from the Object. The console prints "Honda costs 20000"
as both values join in one string.
Wrapping Up
In this article, you learned about Objects in JavaScript and how to work with them.
Here is a quick recap:
- You saw how to make Objects and reach values
- You also understood how to add keys and remove keys or loop through data, and use nested data.
- You also saw destruct, methods, and real code examples
FAQs
How to create a JavaScript Object?
let person = { name: "John", age: 30 };
console.log(person.name); // Output: John
How to access properties in a JavaScript Object?
let car = { brand: "Toyota", model: "Corolla" };
console.log(car.brand); // Dot notation, Output: Toyota
console.log(car["model"]); // Bracket notation, Output: Corolla
How to add or update properties in a JavaScript Object?
let user = { username: "alice" };
user.age = 25; // Add property
user.username = "bob"; // Update property
console.log(user); // Output: { username: "bob", age: 25 }
How to loop through all properties of a JavaScript Object?
let book = { title: "JS Guide", pages: 200 };
for (let key in book) {
console.log(key + ": " + book[key]);
}
// Output:
// title: JS Guide
// pages: 200
Similar Reads
JavaScript gives you the Math.round() function to deal with decimal numbers. You use it when you want to round a…
AJAX keeps your web app fast. You do not need to reload the page every time you send or get…
JavaScript Math.sqrt() solves the need to get square roots fast. Before it, you wrote custom code or used loops. It…
You need to compare values in almost every JavaScript program. This is where comparison operators come in. They check if…
JavaScript includes Math.sign to find out if a number is positive. It also helps detect negative values or zero. It…
If you are ready to take your first steps into the realm of web development, then there cannot be a…
Code mistakes used to slip by without a warning. That made bugs hard to trace and fix. JavaScript "use strict"…
Some numbers do not stay whole. You get decimal parts when you divide or calculate prices. You may need to…
The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you…
JavaScript runs code in different ways, but the for loop stays one of the most common tools. You use it…