Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a multidimensional array value assignation works in this case?

Why this function does not return an string with the first letter of each word on upper case?

function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i][0] = str[i][0].toUpperCase(); 
         console.log(str);
     }
     return str;
}
like image 635
OzzoN Avatar asked Feb 02 '26 02:02

OzzoN


1 Answers

The reason Why this function does not return an string with the first letter of each word on upper case is because strings are immutable.

You cannot change a character within a string.

Therefore this does not work in javascript:

str[i][0] = 'c';

This does not change the string str[i].

However in order to achieve your goal you can make a new string with first letter uppercase and assign it to the variable containing your string.

like image 108
Rohit Agrawal Avatar answered Feb 03 '26 16:02

Rohit Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!