Why You Can’t Just Modify an Index of a String

Difference between a String and an Array in Javascript, even though they behave alike.

Buddhi Vikasitha
2 min readDec 24, 2023

I recently forgot an important Javascript fundamental and tried the following.

myString[0] = 's'; //myString is a String

I embarrassed myself by running the code and expecting to modify the index of a string like this. But we cannot modify a string this way because Javascript has different ways of treating different values.

In most cases we can treat strings and arrays in Javascript similarly. It is even easier to visualize them with similar data structures to better understand our code but there is an important thing to remember.

Arrays are Objects

Strings are Primitive Values

In Javascript, there are 7 primitive values and strings are one of them.

  1. string
  2. number
  3. bigint
  4. boolean
  5. undefined
  6. symbol
  7. null

There are not objects and has no methods or properties. Hence these are immutable. Most of the time, a primitive value is represented directly at the lowest level of the language implementation. Arrays in the other hand are treated as objects in Javascript so that they expose methods and properties, and they are also mutable.

But if strings have no methods or properties, how can we do the following in our code?

let stringVariable = otherStringVariable.substring();
console.log(stringVariable.toUpperCase());

When a primitive is accessed, most of the time Javascript auto-boxes the primitive into a wrapper object. In this scenario the string primitive is wrapped with a String object. Then Javascript can call the methods on that object.

Check this example as well.

let a = 10;
console.log(a.toString());
console.log(a.toExponential());

Even the Number wrapper has some methods that we can call after initializing a number variable.

References

I am an AWS, Linux and Scrum Master certified Senior Fullstack Software Engineer at Telzee.io. I am deeply interested in architecture concepts for the Javascript world. Please stop at the website buddhiv.io to visit my profile.

--

--

Buddhi Vikasitha

Software Engineer, Graphic Designer, Gamer, Mahindian, Graduate | buddhiv.io