Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow are characters stored in JavaScript ?

How are characters stored in JavaScript ?

In many languages like C, C++, Java, etc. char is a primitive data type but in JavaScript, there is no special data type to store characters. Internally JavaScript stores characters as String only. In JavaScript, a String of length only is considered a character. Since a character is also a string so character also gets stored in a string constant pool.

The string constant pool is a small cache that resides within the heap. JavaScript stores all the values inside the string constant pool on direct allocation. The string constant pool exists mainly to reduce memory usage and improve the reuse of existing instances in memory.

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

Example 1: In this example, we will store characters in variables.

Javascript




var char1 = 'a';
var char2 = 'a';
var char3 = 'b';
  
console.log(typeof(char1));
console.log(char1 == char2);
console.log(char1 == char3);


Output: Here, we can see that internally all the characters are being stored as String and strings with the same value refer to the same location in the memory to reduce memory usage.

string
true
false

Example 2: In this example, we will store characters with the same value but at different memory locations.

Javascript




var char1 = new String('a');
var char2 = new String('a');
var char3 = 'a';
  
console.log(typeof(char1));
console.log(char1 == char2);
console.log(char1 == char3);


Output: We can observe, that now the character is being stored as an object and each new instance of an object is allocated a new location in the memory even though it contains the same value.

object
false
true

Conclusion:

When we are storing characters using just quotation(”) marks then variables having the same value are stored at same location in the String Constant Pool but if we use new keyword then distinct memory location is assigned to each value even if they have the same value

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