I have been reading here
https://developer.mozilla.org/en-US/docs/JavaScript/Memory_Management#Allocation_via_function_calls
and these lines confused me a bit:
var s = "azerty";
var s2 = s.substr(0, 3); // s2 is a new string
// Since strings are immutable value, JavaScript may decide
// to not allocate memory, but just store the [0, 3] range.
So the comments say, JavaScript may decide to not allocate memory and just store the range [0,3] , Now doesnt memory have to be allocated before storing? in case not, as the comment implies, what exactly happens so that the stored range, gets stored in free space, not occupied already by other values.
The comment means that s2 does not have to allocate memory specifically for the three characters "aze". Instead, it can use the memory already allocated for "azerty" by s and remember that its own length is just three characters.
The immutability part is also important: if s were not immutable then it could decide to change its value from "azerty" to "foobar" without telling anyone, thus also indirectly changing the value of s2 to "foo" -- which would be disastrous.
Of course this does not mean that no memory at all will be allocated; we still need to allocate memory for storing the location where the string's contents can be found, and for the string's length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With