You’re working on a project where you have an array of user objects. Each user object has an age
property. You need to accomplish two tasks:
- Transform the
age
of each user to reflect their age next year. - Log a message indicating whether each user will be a teenager next year (i.e., age between 13 and 19).
Given Data
const users = [
{ name: 'Alice', age: 12 },
{ name: 'Bob', age: 18 },
{ name: 'Charlie', age: 20 }
];
Task 1: Using map
Create a new array that contains the ages of users next year. For example, if a user is 12 years old now, their age next year would be 13.
Task 2: Using forEach
For each user, log a message indicating whether they will be a teenager next year. For instance, “Alice will be a teenager next year.”
Your Task
- Implement the solution for Task 1 using the
map
method. - Implement the solution for Task 2 using the
forEach
method. - Verify that the results are as expected.
Example Solution
Here’s how you might approach this challenge:
// Task 1: Using map
const agesNextYear = users.map(user => user.age + 1);
console.log(agesNextYear); // [13, 19, 21]
// Task 2: Using forEach
users.forEach(user => {
const ageNextYear = user.age + 1;
if (ageNextYear >= 13 && ageNextYear <= 19) {
console.log(`${user.name} will be a teenager next year.`);
}
});
Challenge Steps:
- Write the code to complete both tasks.
- Test your code to ensure it produces the correct output.
- Reflect on the differences in how
map
andforEach
were used. What were the advantages of each method in this scenario?