Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!