Open In App

How are strings stored in JavaScript ?

Last Updated : 17 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will try to understand how strings are stored in JavaScript. Strings are a primitive data type in JavaScript and are allocated a special place in memory to store and manipulate. Unlike some other languages, JavaScript does not have a String Constant Pool. Instead, JavaScript engines manage strings efficiently within the memory using various optimizations.

In other words, modern JavaScript engines may optimize the storage and reuse of string literals to reduce memory usage and improve performance. However, this is not the same as a String Constant Pool.

There are some cases where we want a distinct String object to be created even though it has the same value. In this case, we use the new keyword. However, this creates a String object rather than a primitive string, which is generally not recommended.

Let us now understand with a basic example, how strings are stored in memory.

Example 1: In this example, we will create Strings and understand how they are stored in memory.

JavaScript
let str1 = "Hello";
let str2 = "Hello";
let str3 = "World";
console.log(str1 == str2);
console.log(str1 == str3);

Output:

true
false

Below is the diagrammatic representation of how the strings in the above example will be stored in memory.

How are strings stored in javascript?

How are strings stored in javascript?

We can see that str1 and str2 point at the same location in the memory while a new space is created for str3 as it has a different value. In this way string constant pool saves memory by making the same value string point to the same location in the memory.

Example 2: In this example, we will make the strings with the same value refer to different locations in memory

JavaScript
let str1 = new String("John");
let str2 = new String("John");
let str3 = new String("Doe");
console.log(str1 == str2);
console.log(str1 == str3);

Output:

false
false
How are strings stored in javascript?

How are strings stored in javascript?

We can see in the image that even though str1 and str2 are having the same value but because of the new keyword they are referring to different locations in the memory. Hence, they return false when compared.

Conclusion:

When creating the strings using quotations(” “) they are directly stored in the String Constant Pool where equal values refer to the same location in the memory. Whereas, when strings are created using the new keyword, a new instance is always created in the heap memory then the value is stored in the String Constant Pool because of this even if the data stored is the same still the strings will not be equal.  



Similar Reads

three90RightbarBannerImg
  翻译: