How are characters saved in JavaScript ?

0
12
Adv1


Adv2

Enhance Article

Save Article

Like Article

Enhance Article

Save Article

Like Article

In lots of languages like C, C++, Java, and so on. char is a primitive knowledge kind however in JavaScript, there isn’t any particular knowledge kind to retailer characters. Internally JavaScript shops characters as String solely. In JavaScript, a String of size solely is taken into account a personality. Since a personality can also be a string so character additionally will get saved in a string fixed pool.

The string fixed pool is a small cache that resides throughout the heap. JavaScript shops all of the values contained in the string fixed pool on direct allocation. The string fixed pool exists primarily to scale back reminiscence utilization and enhance the reuse of current situations in reminiscence.

Allow us to now perceive with a primary instance, how characters are saved in reminiscence.

Instance 1: On this instance, we are going to retailer 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: Right here, we are able to see that internally all of the characters are being saved as String and strings with the identical worth seek advice from the identical location within the reminiscence to scale back reminiscence utilization.

string
true
false

Instance 2: On this instance, we are going to retailer characters with the identical worth however at totally different reminiscence areas.

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 are able to observe, that now the character is being saved as an object and every new occasion of an object is allotted a brand new location within the reminiscence regardless that it comprises the identical worth.

object
false
true

Conclusion:

Once we are storing characters utilizing simply citation(”) marks then variables having the identical worth are saved at similar location within the String Fixed Pool but when we use new key phrase then distinct reminiscence location is assigned to every worth even when they’ve the identical worth

Like Article

Save Article

Adv3