TL&DRs: What I know about JavaScript String.

ยท

2 min read

Hey! What do you know about string type in JavaScript? I believe you saw gazillion times about 1+'1' or so. In this article, I won't talk about it, but I'd suggest we cover these questions:

  1. How strings are stored?

  2. Is there a limit for the string length?

  3. Is it possible to overflow the call stack?

How are strings stored?

๐Ÿ“ Strings are stored in Heap. There is a special place for all the strings you're using: string pool:

Use DevTools console + memory tab to check how the string pool allocates memory:

  1. Open about://blank page

  2. Paste code like this (but do not execute it):

  3.  const a = 'hello';
     const b = 'world';
     const c = a + b;
     const d = 'hello'
    
  4. Go to the memory tab and take the first heap snapshot. You will get something like this:

  5. Execute the pasted code and take the second snapshot. You can compare snapshots using the select menu on top:

  6. You can see that hello, world and their concatenation were used only once.

Is there a limit for the string length?

๐Ÿ“ Yes, in V8 (node.js, chrome, etc.) there is a limit of 512Mb:

It was done by using:

const a = Array.from({length: MB64}).join('a')
b = a + a + a + a + a + a + a + a

Further increase in length would lead to the Invalid string lengthexception:

๐Ÿ“ Be careful while processing big JSON entities or huge files in Node.JS or Chrome environment. You might need to use streams / binary blobs while reading data, instead of strings.

๐Ÿ“ Firefox at the same time doesn't have such a limit. You can see on a screenshot a string with about 1GB length:

Is it possible to overflow the stack using strings?

As strings are stored in a heap, the answer is no.

The only thing how you can overflow the stack is by creating too many references, like that:

More context about this trick: https://blog.xnim.me/js-call-stack-size-exceeded

ย