For in object question

Another Intermediate Algorithm Challenge. I got it to work using a switch nested in a for loop but couldn’t manage with the for in method. I’m trying to have the forEach compare each element in the array to, using the for in, every key in the object. If the element === key, then change the element to the object key’s value.

I consoled everything out as much as I could, but it doesn’t want to work in the forEach loop.

function convertHTML(str) {
  let arr = str.split('');

  const entities = {
    '&': '&',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&apos;',

  arr.forEach((elem) => {
    for (let obj in entities) {
      if (elem == obj) {
        console.log(elem, obj);
        elem = entities[obj];

  return arr.join('');

I’ve formatted your code for readability.

Also, please link to the challenge when asking for help, or use the ask for help button.

You can’t change the element value like you are trying to do. You can mutate the array if you use the array and the index.

const numbers = [1, 2, 3, 4];

numbers.forEach((number, index) => {
  if (number % 2 === 0) {
    console.log(number); // 2, 4
    number = 42;
  } else {
    console.log(number); // 1, 3
    numbers[index] = 42;

console.log(numbers); // [ 42, 2, 42, 4 ]
1 Like

So in
arr.forEach( elem => {});
elem can’t be used to mutate the array with a simple assignment operator (elem = 10, for example). But it can be used to refer to the elements of the array in other ways.?

elem here is not exactly the element of the array, rather it’s an argument to callback function you’re passing to forEach() and depending on the type of the element it might be passed “by value”, meaning changing it will not affect original. You can read more about this here:

1 Like

forEach is not the only method on Array.prototype by the way, have a look and see if you can find one that does exactly what you’re trying to do :wink:

Thanks–I am trying to get out of my comfort zone of using for loops for everything! These higher order methods are more complex and I guess it will take a while for me to get the hang of them.