Question on one exercise in the JavaScript Useful String Methods Tutorial

I have a question regarding one of the Fixing capitalization exercise in the JavaScript Useful String Methods Tutorial.

I understand the solution code, but I tried something else that didn’t follow the instructions given. I don’t know why it doesn’t work. Basically, the only thing I did form the starting point is adding these two lines:

input = input.toLowerCase();
input[0] = input[0].toUpperCase();

So the entire code looks like this:

const list = document.querySelector('.output ul');
list.innerHTML = '';
let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL'];

for (let i = 0; i < cities.length; i++) {
  let input = cities[i];
  // write your code just below here
  input = input.toLowerCase();
  input[0] = input[0].toUpperCase();

  let result = input;
  let listItem = document.createElement('li');
  listItem.textContent = result;
  list.appendChild(listItem);
}

I feel like this would make sense in R and Python, but somehow it doesn’t work here and I’m not sure why.

Is it because strings in JavaSCript act more like tuples and not lists in Python, so we aren’t allowed to change its content. And functions like .toUpperCase() and .replace() are actually creating new objects and using new memory space?

@saralin10co Hey there!

Yeah, in terms of why this doesn’t work, you are basically correct. It is all down to the string getter syntax (e.g. input[0]) only being a getter - you are basically accessing a character of a string in read-only fashion, plus the fact that, as you say, methods like replace() crete a new version of the string, rather than altering the original object.

Saying this, your comments did make me have a think about a simpler way to do this than what I have for my solution.

the following works:

const list = document.querySelector('.output ul');

list.innerHTML = '';

let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL'];



for (let i = 0; i < cities.length; i++) {

  let input = cities[i];

  // write your code just below here

  input = input.toLowerCase();
  var newInput = input.replace(input[0],input[0].toUpperCase());

  let listItem = document.createElement('li');
  listItem.textContent = newInput;
  list.appendChild(listItem);

}
1 Like