danwhite85
1/29/2013 - 5:30 AM

JS Memory

JS Memory

JavaScript Code

var str = "hi";

Memory allocation:

AddressValueDescription
.........
0x1001call objectStart of a call object's memory
0x10020x00afReference to invoked function
0x10031Number of references in this call object
0x1004strName of variable (in practice would not be in a single address)
0x10050x1001Memory address of "hi"
.........
0x2001stringtype identifier
0x20022number of bytes
0x2003hbyte of first character
0x2004ibyte 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:

AddressValueDescription
.........
0x1001call objectStart of a call object's memory
0x10020x00afReference to invoked function
0x10031Number of references in this call object
0x1004strName of variable
0x1005empty
.........

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:

AddressValueDescription
.........
0x2001stringtype identifier
0x20022number of bytes
0x2003hbyte of first character
0x2004ibyte 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.