Thursday, December 26, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Strings Read Only

JavaScript Strings Read Only

In this article, we will try to answer a major question that arises with working in JavaScript. Are the Strings read-only in JavaScript?

In JavaScript Strings are a primitive data type that are used to store an array of characters. The Strings in JavaScript have a special trait that the strings are read-only. Read-only means that the strings created in JavaScript are immutable. Once the string is assigned a value, it cannot be altered. When we try to manipulate strings using methods such as trim(), replace(), and slice(), instead of manipulating the string a new string with manipulated values is returned. Even if we use index-based manipulation it will not work on strings.

To understand why these Strings are immutable, we will have to understand how Strings are stored in memory. When strings are created the individual characters are assigned contiguous memory blocks which cannot be modified or resized without creating a new block in the memory to store new strings with changes.

The read-only property has another benefit because we can easily work with strings in multiple parts of the program without worrying about any change in the original value of the string.  

Note: To create a String, we can put the data in quotes(” “) or use the String constructor.

Let us look at a few examples to see the read-only nature of JavaScript Strings.

Example 1:  This example tries to manipulate a string using an index.

Javascript




const str1 = new String("Hello GFG");
const str2 = "Welcome to GFG";
  
str1[2] ="g";
str2[2] = "y";
  
console.log(str1);
console.log(str2);


Output:  When we try to manipulate the string using the index the original string remains the same.

String {'Hello GFG'}
Welcome to GFG

Example 2: This example manipulates String using string methods.

Javascript




const str1 = new String("Hello GFG");
  
str1.slice(0, 5);
str1.replace("Hello", "Bye");
  
const str2 = str1.replace("Hello", "Bye");
  
console.log(str1);
console.log(str2);


Output: Instead of manipulating the original string this method returns a new string with the manipulated value

String {'Hello GFG'}
Bye GFG

Conclusion: Hence, we can conclude that the strings are read-only as they cannot be modified without creating a new string. Changing values without creating a new string is impossible.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments