Skip to content

Instantly share code, notes, and snippets.

@justinbmeyer
Last active June 29, 2024 16:00
Show Gist options
  • Select an option

  • Save justinbmeyer/4662050 to your computer and use it in GitHub Desktop.

Select an option

Save justinbmeyer/4662050 to your computer and use it in GitHub Desktop.
JS Memory

JavaScript Code

var str = "hi";

Memory allocation:

Address Value Description
...... ...
0x1001 call object Start of a call object's memory
0x1002 0x00af Reference to invoked function
0x1003 1 Number of references in this call object
0x1004 str Name of variable (in practice would not be in a single address)
0x1005 0x1001 Memory address of "hi"
...... ...
0x2001 string type identifier
0x2002 2 number of bytes
0x2003 h byte of first character
0x2004 i byte of second character

Explanation

When JS runs: var str = "hi"; by calling some function, it first hoists all variable declarations and creates a spot in memory for the variable. This might leave memory something like:

Address Value Description
...... ...
0x1001 call object Start of a call object's memory
0x1002 0x00af Reference to invoked function
0x1003 1 Number of references in this call object
0x1004 str Name of variable
0x1005 empty
...... ...

In practice, the name of the variable, str, would not be held in a single memory address. Also, the variable names and locations would not be stored in a fixed-memory array (possibly in a hash-table).

Next, the string "hi" would be created in memory like:

Address Value Description
...... ...
0x2001 string type identifier
0x2002 2 number of bytes
0x2003 h byte of first character
0x2004 i byte of second character

Finally, the pointer address of str would be set to the memory address of "hi" (0x2001), leaving memory as indicated at the top of the page.

@martianmartian
Copy link

i would really appreciate it if someone can help me to check my understanding of this whole process. i wrote them down here, here, and here. Justing wondering coz these things have been bugging me for a while.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment