Skip to content

JavaScript string immutable | Basics

  • by

JavaScript string are immutable objects means once a String object is assigned to String reference the object value cannot be changed.

You can’t change a character within a string with something like:

var myString = "abcdef"; 
myString[0] = 'c';

The string manipulation methods such as trim, slice return new strings.

In the same way, if you have two references to the same string, modifying one doesn’t affect the other

let a = b = "hello";
a = a + " world";
// b is not affected

JavaScript string immutable

Simple example code.

<!DOCTYPE html>
<html lang="en">
   let string1 = 'hello';
   let string2 = string1;

   console.log('string1 ->', string1);
   console.log('string2 ->', string2);

  console.log('string1 === string2 ->', string1 === string2); // true

  string1.concat(' world!');
  console.log('string1 ->', string1); // still just 'hello', because `concat` doesn't (and cannot) mutate the original string

  string1 = string1.concat(' world!'); // change by reassignment
  console.log('string1 ->', string1); // *now* it reflects the change

  // but now string 1 and string 2 are different
  console.log('string1 ->', string1);
  console.log('string2 ->', string2);

  // and not equal
  console.log('string1 === string2 ->', string1 === string2);

  // also, since they are immutable, strings are just compared by *value*, so we can do this

  console.log('"hello" === string2 ->', "hello" === string2); //true


JavaScript string immutable

Do comment if you have any doubts or suggestions on this JS string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *