-3

I am trying to change the entire word into capital letters. What is wrong with my approach, for individual letters toUpperCase is working fine

var name = "gates";
for (var i=0; i< name.length; i++){
name[i] = name[i].toUpperCase();
}
name;

So the thing is "hello world".toUpperCase() is working fine as expected. Why the looping individual characters in array does not work as expected!. Is this some property in arrays/strings especially in JS?

As RGraham mentioned the string letters cannot be modified, I don't understand the negative feedback of the community. Even the question seems to be valid.

gates
  • 4,465
  • 7
  • 32
  • 60

5 Answers5

4

The reason this doesn't work, is that accessing a string using the array syntax is read-only. As per the MDN docs:

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See Object.defineProperty() for more information.)

So, console.log(name[0]) will work, but name[0] = "G"; will not update the name variable.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
2

You don't need to loop through the letters, just do:

var name = "gates";
name = name.toUpperCase();
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
2

A string is immutable in most languages, meaning, you can't change individual characters, or add something, without ending up with a new one.

name = name.toUpperCase();

Will give you what you need, but a new, all-caps string is put in the variable 'name'.

Joachim VR
  • 2,320
  • 1
  • 15
  • 24
1

Accoring to http://www.w3schools.com/jsref/jsref_touppercase.asp

var str = "Hello World!";
var res = str.toUpperCase();
bwright
  • 896
  • 11
  • 29
1

http://www.w3schools.com/jsref/jsref_touppercase.asp

var str = "Hello World!";
var res = str.toUpperCase();

Result:

HELLO WORLD!
The_Monster
  • 494
  • 2
  • 7
  • 28