Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
Why I can't change element of the array in forEach()?

Here's my function. It's supposed to return backgroundColor instead of backgroundcolor.

What's my problem?

function camelize(str) {
  let newStr = str.split('-');
  newStr.forEach((item, index) => {
    if (index > 0) {
      item.toLowerCase();
      item = item[0].toUpperCase() + item.slice(1);
    }
  });

  newStr = newStr.join('');
  return newStr;
}
console.log(camelize("background-color")); //'backgroundсolor' instead of 'backgroundColor'

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

  1. You need a map
  2. you need to return the item

I simplified the code

const camelize = str => str
  .toLowerCase()
  .split('-').map((item, index) => index > 0 ? 
      item[0].toUpperCase() + item.slice(1) : item)
  .join('');

console.log(camelize("background-color")); 
console.log(camelize("Background-color")); 
console.log(camelize("BACKGROUND-COLOR")); 

Closer to your old code

function camelize(str) {
  const parts = str.toLowerCase().split('-');
  let newStr = parts.map((item, index) => {
    if (index > 0) {
      item = item[0].toUpperCase() + item.slice(1);
    }
    return item
  });

  newStr = newStr.join('');
  return newStr;
}
console.log(camelize("background-color"));

about 4 years ago · Juan Pablo Isaza Denunciar

0

item is a local variable inside the function. Assigning to it has no effect on newStr.

item.toLowerCase() returns a new string, it doesn't modify the string in place (JS strings are immutable). You need to assign it back to the variable to change it.

Use map() instead of forEach() so you return a new array with the results.

function camelize(str) {
  let oldStr = str.split('-');
  let newStr = oldStr.map((item, index) => {
    if (index > 0) {
      item = item.toLowerCase();
      item = item[0].toUpperCase() + item.slice(1);
    }
    return item;
  });

  return newStr.join('');
}
console.log(camelize("background-color")); //'backgroundсolor' instead of 'backgroundColor'

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda