Are JavaScript strings immutable?

Angelos Chalaris · JavaScript, String, Type · Oct 10, 2021

String specifications among programming languages vary, however most languages treat them as reference types. But strings in JavaScript are different. They are immutable primitives. This means that the characters within them may not be changed and that any operations on strings actually create new strings.

const x = 'type';
x[1] = 'a';       // Nothing happens, doesn't throw an error
console.log(x);   // LOGS: 'type'

It helps to think of strings in the way that we think of numbers, if we are to better understand how they work. Numeric values are also immutable primitives. If, for example, you could mutate numbers, you could change the meaning of the value 42 to be another number, say 13. In the same sense, you cannot mutate a string with a value of gem to make it gym.

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets & collections

  • Prepare for your next JavaScript interview with this collection of interview questions and answers.

  • Word wrap string

    JavaScript, String

    Wraps a string to a given number of characters using a string break character.

  • CSV to JSON

    JavaScript, String

    Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.

  • Index of substrings

    JavaScript, String

    Finds all the indexes of a substring in a given string.