Lesson 16: Introduction to JavaScript Objects
What is an Object?
An object in JavaScript is a collection of key-value pairs. Each key is called a property, and each value can be a string, number, array, function, or even another object.
Objects help us structure and organize data meaningfully.
Example 1: Creating an Object
const person = {
name: "Alice",
age: 25,
city: "New York"
};
console.log(person.name); // Output: Alice
console.log(person.age); // Output: 25
console.log(person.city); // Output: New York
???? The object person
has three properties: name
, age
, and city
.
Example 2: Adding and Modifying Properties
const car = { brand: "Toyota", model: "Corolla" };
// Adding a new property
car.year = 2022;
// Modifying an existing property
car.model = "Camry";
console.log(car);
// Output: { brand: "Toyota", model: "Camry", year: 2022 }
???? We can add new properties and update existing ones dynamically.
Example 3: Object Methods (Functions Inside Objects)
const user = {
name: "John",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
user.greet();
// Output: Hello, my name is John
???? We added a method (function) inside the object using this
to refer to the object itself.
Explanation
Objects allow us to store multiple related pieces of data in a single entity. Unlike arrays, which use numeric indices, objects use named keys to organize values.
- Objects are enclosed in
{}
(curly braces). - Each key is followed by a colon
:
and its corresponding value. - Key-value pairs are separated by commas
,
. - Values can be any data type (numbers, strings, arrays, functions, or even other objects).
Objects are useful for grouping related information, such as details about a person, car, or user profile.
Try Your Hand
Let's practice creating objects and using their properties.
Steps:
-
Create a File:
- Create a new file named
lesson16-objects.html
.
- Create a new file named
-
Write the Code:
- Copy and paste the following code into your file:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 16 - JavaScript Objects</title> </head> <body> <script> const laptop = { brand: "Dell", model: "XPS 15", price: 1500 }; console.log("Laptop Brand:", laptop.brand); console.log("Laptop Model:", laptop.model); console.log("Laptop Price: $" + laptop.price); laptop.price = 1400; // Updating the price console.log("Discounted Price: $" + laptop.price); </script> </body> </html>
-
Save the File:
- Save the file in your folder.
-
Preview the File:
- Open the file in your browser and check the console for the output.
Experiment
Try modifying the object properties dynamically using JavaScript.
-
Modify an existing property:
laptop.model = "MacBook Pro"; console.log("Updated Model:", laptop.model);
-
Add a new property:
laptop.color = "Silver"; console.log("Laptop Color:", laptop.color);
Observe the changes in your browser console.