0% found this document useful (0 votes)
21 views

Lab - Understanding JavaScript Objects

Uploaded by

komoireashiraf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Lab - Understanding JavaScript Objects

Uploaded by

komoireashiraf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lab: Understanding JavaScript Objects

Objectives:

1. Learn what objects are and how to define them in JavaScript.


2. Understand how to access and manipulate object properties.
3. Learn how to use methods within objects.
4. Explore real-world applications of objects using Ugandan contexts.
5. Practice creating and working with objects in various scenarios.

Part 1: Introduction to Objects in JavaScript

In JavaScript, an object is a collection of related data and functions (methods) stored together.
Objects allow us to model real-world entities and can be used to represent anything from a
person to a city.

Syntax for Creating an Object

let objectName = {
property1: value1,
property2: value2,
method1: function() {
// method code
}
};

Part 2: Creating and Accessing Object Properties

Example 1: Object for a Ugandan Farmer

Let's create an object representing a farmer in Uganda.

let ugandanFarmer = {
name: "James",
farmLocation: "Mbale",
crop: "Coffee",
numberOfAcres: 5
};
// Accessing properties
console.log(`Farmer's Name: ${ugandanFarmer.name}`);
console.log(`Farm Location: ${ugandanFarmer.farmLocation}`);

Task 1:
Create an object school that has properties like name, location, studentsCount, and
establishedYear. Log the school’s name and location to the console.

Part 3: Adding and Modifying Object Properties

Once an object is created, you can add new properties or modify existing ones.

Example 2: Modifying a Farmer's Object

ugandanFarmer.cropsHarvested = 1000; // Adding a new property


ugandanFarmer.crop = "Maize"; // Modifying an existing property
console.log(ugandanFarmer);

Task 2:
Using the school object from Task 1, add a new property schoolType (either "Primary" or
"Secondary") and change the studentsCount. Log the updated object.

Part 4: Methods in Objects

A method is a function stored as a property in an object. Methods allow objects to perform


actions.

Example 3: Adding a Method to Calculate Farm Revenue

let ugandanFarmer = {
name: "James",
farmLocation: "Mbale",
crop: "Coffee",
numberOfAcres: 5,
cropPrice: 3000,
calculateRevenue: function(harvestedBags) {
return harvestedBags * this.cropPrice;
}
};

let revenue = ugandanFarmer.calculateRevenue(200);


console.log(`Total revenue for ${ugandanFarmer.crop} is UGX
${revenue}`);

Task 3:
Add a method calculateSchoolAge to the school object that calculates the age of the
school based on the current year. Use this method to calculate and print the school's age.

Part 5: Nested Objects

Objects can contain other objects. This is useful when modeling complex entities.

Example 4: Nested Object for a Ugandan City

let kampalaCity = {
name: "Kampala",
population: 1500000,
districts: {
central: "Kampala Central",
east: "Nakawa",
north: "Kawempe",
south: "Makindye",
west: "Rubaga"
}
};

console.log(`District in the north of Kampala:


${kampalaCity.districts.north}`);

Task 4:
Create a university object that contains nested objects for departments, with each
department having a name and headOfDepartment. Log the head of one of the departments.
Part 6: Looping Through Objects

We can use the for...in loop to iterate over the properties of an object.

Example 5: Iterating Over a Farmer's Properties

let ugandanFarmer = {
name: "James",
farmLocation: "Mbale",
crop: "Coffee",
numberOfAcres: 5
};

for (let key in ugandanFarmer) {


console.log(`${key}: ${ugandanFarmer[key]}`);
}

Task 5:
Using the school object from previous tasks, loop through all properties and log them to the
console.

Part 7: Object Methods and the this Keyword

In object methods, the this keyword refers to the object the method belongs to.

Example 6: Using this in a Method

let ugandanFarmer = {
name: "James",
farmLocation: "Mbale",
crop: "Coffee",
numberOfAcres: 5,

introduceFarmer: function() {
return `Hello, my name is ${this.name} and I farm ${this.crop}
in ${this.farmLocation}.`;
}
};

console.log(ugandanFarmer.introduceFarmer());

Task 6:
Add a method schoolIntroduction to the school object that returns a string introducing
the school’s name, location, and number of students using the this keyword.

Part 8: Object Constructors

A constructor function is used to create multiple objects with similar properties and methods.

Example 7: Creating Multiple Farmers Using a Constructor

function Farmer(name, location, crop, acres) {


this.name = name;
this.farmLocation = location;
this.crop = crop;
this.numberOfAcres = acres;
this.introduce = function() {
return `I am ${this.name}, and I farm ${this.crop} in
${this.farmLocation}.`;
};
}

let farmer1 = new Farmer("Sarah", "Mbarara", "Bananas", 10);


let farmer2 = new Farmer("David", "Gulu", "Sunflowers", 20);

console.log(farmer1.introduce());
console.log(farmer2.introduce());

Task 7:
Create a constructor function School that takes in the name, location, studentsCount,
and schoolType. Create two new school objects and introduce them.

Part 9: Object Destructuring


Destructuring allows us to unpack properties from an object into variables.

Example 8: Destructuring an Object

let ugandanFarmer = {
name: "James",
farmLocation: "Mbale",
crop: "Coffee"
};

let {name, farmLocation, crop} = ugandanFarmer;


console.log(`${name} farms ${crop} in ${farmLocation}.`);

Task 8:
Using the school object, destructure the name, location, and studentsCount into
variables and log them.

Part 10: Real-World Example: Modeling a Ugandan Business

Let’s create a more complex example of a Ugandan business selling different products.

Example 9: Business Object

let business = {
name: "Kampala Electronics",
location: "Kampala",
products: [
{ name: "TV", price: 1000000, quantity: 50 },
{ name: "Radio", price: 150000, quantity: 200 },
{ name: "Laptop", price: 3000000, quantity: 30 }
],

calculateTotalValue: function() {
let total = 0;
for (let i = 0; i < this.products.length; i++) {
total += this.products[i].price *
this.products[i].quantity;
}
return total;
}
};

console.log(`Total value of products in stock: UGX


${business.calculateTotalValue()}`);

Task 9:
Create an object for a marketVendor who sells multiple products (e.g., bananas, cassava,
tomatoes). Each product should have a price and quantity. Add a method to calculate the
total revenue for all products in stock.

Lab Summary:

In this lab, we have:

● Explored how to create, access, and modify objects and their properties.
● Learned how to add methods to objects and use the this keyword.
● Created nested objects and used loops to iterate through object properties.
● Explored constructor functions to create multiple objects and destructured objects.
● Applied object concepts to real-world scenarios, including farming, schools, and
businesses.

Additional Exercises:

1. Create an object representing a boda-boda rider. Include properties like name,


location, and bodaType, and add a method to calculate the rider's income for a day
based on the distance traveled and the fare per kilometer.
2. Model a Ugandan football team using objects. Each player should have properties like
name, position, and goalsScored, and the team should have a method to calculate
the total goals scored by all players.
3. Write a constructor function for a Hospital object in Uganda, with properties like name,
location, numberOfBeds, and a method to calculate the total capacity based on the
number of wards and beds per ward.

This lab will provide a comprehensive understanding of how to work with JavaScript objects
while using relatable Ugandan

You might also like