Replace an employee aged > 50 with a younger employee.
I am trying to update an item inside an array I am forEach()ing on. Assigning the current fails while noting the index and replacing the item after forEach() block works. Kindly explain this behaviour?
var youngerEmployee = {
  name: {
    first: 'B',
    last: 'C'
  },
  age: 25
}
var employees = [
  {
    name: {
      first: 'X',
      last: 'Y'
    },
    age: 45
  },
  {
    name: {
      first: 'A',
      last: 'B'
    },
    age: 54
  }
];
/* --- Failed approach --- */
employees.forEach(
  (employee) => {
    if(employee.age > 50) {
      employee = youngerEmployee;
    }
  }
);
console.log(employees);
/* --- Successful approach --- */
var i = -1;
employees.forEach(
  (employee, index) => {
    if(employee.age > 50) {
      i = index;
    }
  }
);
employees[i] = youngerEmployee;
console.log(employees);
 
     
    