J080 Simple Object Usage
A basic exploration into how objects are used and manipulated in ES (ECMAScript).
Within your app.js:
Task:
- Create an object named
person. - Add a
nameand anageproperty to thepersonobject. - Define a function that can print the details of the
personobject. For example: - “I am called [name] and I am [age] years old.”
- Call this function to display the details.
Solution
"use strict";
// Create a person object with name and age properties
const person = {
name: 'John',
age: 25
};
// Function to print details of a person
function displayPersonDetails(p) {
console.log(`I am called ${p.name} and I am ${p.age} years old.`);
}
// Call the function
displayPersonDetails(person);
// Bonus: Modify the age of the person and call the function again
person.age = 30;
displayPersonDetails(person);
This exercise gives a basic introduction to objects in JavaScript and how they can be passed to functions as arguments. The bonus step adds a little more complexity and shows how we can modify properties of objects.