Challenge on Data Transformation and Side Effects

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:

  1. Transform the age of each user to reflect their age next year.
  2. 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

  1. Implement the solution for Task 1 using the map method.
  2. Implement the solution for Task 2 using the forEach method.
  3. 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:

  1. Write the code to complete both tasks.
  2. Test your code to ensure it produces the correct output.
  3. Reflect on the differences in how map and forEach were used. What were the advantages of each method in this scenario?

Leave a Reply

Your email address will not be published. Required fields are marked *