javascriptintermediate10 minutes

Refactor the User Data Formatter Function for Better Readability and Performance

Improve a given JavaScript function that formats an array of user objects by cleaning up nested conditionals, reducing duplication, and enhancing readability while keeping the output unchanged.

Challenge prompt

You have been given a function that processes an array of user objects and returns a formatted array of strings combining user details. The current implementation uses nested conditionals and repeated code which makes it hard to read and maintain. Refactor the function to improve code readability and maintainability without changing its behavior or output. Example input: [{ name: 'Alice', age: 30, isAdmin: true }, { name: 'Bob', age: 25, isAdmin: false }] Expected output: ['Alice (Admin) - 30 years old', 'Bob - 25 years old']

Guidance

  • Simplify nested conditionals using clearer logic or ternary operators.
  • Avoid repeated code by storing repeated values in variables.
  • Use modern JavaScript features such as template literals for string building.

Hints

  • Consider using map() to iterate and transform the array.
  • Extract repeated parts of the string to variables before conditionals to minimize duplication.

Starter code

function formatUsers(users) {
  const result = [];
  for (let i = 0; i < users.length; i++) {
    let userString = '';
    if (users[i].isAdmin) {
      if (users[i].age) {
        userString = users[i].name + ' (Admin) - ' + users[i].age + ' years old';
      } else {
        userString = users[i].name + ' (Admin)';
      }
    } else {
      if (users[i].age) {
        userString = users[i].name + ' - ' + users[i].age + ' years old';
      } else {
        userString = users[i].name;
      }
    }
    result.push(userString);
  }
  return result;
}

Expected output

['Alice (Admin) - 30 years old', 'Bob - 25 years old']

Core concepts

refactoringarray iterationconditional logictemplate literals

Challenge a Friend

Send this duel to someone else and see if they can solve it.