Translation of this article:
JavaScript ‘s Memory Model


Thanks to the original author for creating such a good article


As developers, we declare variables every day, initialize variables, and assign new values later.



// declare some variables and initialize them
var a = 5let b = 'xy'
const c = true// assign new values
a = 6
b = b + 'z'
c = false // TypeError: Assignment to constant variableCopy the code

However,

In fact

What happens when you do that?
In particular, how does JavaScript handle such basic functionality internally?
More importantly, as a developer, what are the benefits of knowing the nuts and bolts of JavaScript?

Next, I would like to introduce the following

  1. JS primitive data type variable declaration and assignment

  2. JavaScript memory model: call stack and heap

  3. JS references variable declarations and assignments of data types

  4. Let and const

JS primitive data type variable declaration and assignment

Let’s start with a simple example.
Next, we declare a name called
myNumberAnd initialize it to 23.

let myNumber = 23Copy the code

After executing this code, JS will…

  1. Create a unique identifier (” myNumber “) for the variable.

  2. Allocates an address in memory (to be allocated at run time).

  3. Store a value (23) in the assigned address.



Although we colloquially say “myNumber is equal to 23,” procedurally,
myNumber Is equal to the
Save the memory address with the value 23. This is the key difference to understand.

If we were to create a new variable named “newVar” and assign it “myNumber”…

let newVar = myNumberCopy the code

… Due to the
myNumberIt’s going to be equal to
"0012 ccgwh80", so
newVarIs equal to the
"0012 ccgwh80", this is the memory address that holds the value 23.
Ultimately, this is the same as saying, “newVar is now equal to 23.”



Due to themyNumberIs equal to memory address"0012 ccgwh80", so assign it tonewVarwill"0012 ccgwh80"Assigned tonewVar.

Now, what happens if I do this:

myNumber = myNumber + 1Copy the code

"MyNumber"Must be 24. But will newVar also have the value 24 if it points to the same memory address?

The answer is:
Don’t.
Since the raw data types in JS are immutable, when “myNumber + 1” is resolved to “24”, JS will allocate a new address in memory and store its value as 24, and “myNumber” will point to the new address.



Here’s another example:

let myString = 'abc'myString = myString + 'd'Copy the code

A newbie JS might say that wherever in memory, the letter D is simply appended to the string ABC, but this is programmatically incorrect.


When “ABC” is concatenated with “d”, since the string is also the original data type in JS, a new memory address is allocated where “abcd” is stored, and “myString” points to this new memory address.



The next step is to see where memory allocation occurs for primitive data types.

JavaScript memory model: call stack and heap

For the purposes of this blog, you can think of the JS memory model as having two distinct regions: the call stack and the heap.

The call stack is where the raw data types are stored
After declaring variables in the previous section, here is a rough representation of the call stack.



In the illustration below, I strip out the memory address to show the value of each variable.
However, don’t forget that the variable actually points to a memory address that then holds a value.
This is to understand
let
constThe key.

What about the heap.

The heap is where reference data types are stored.
The key difference is that the heap can store unordered data that can grow dynamically, which is perfect for arrays and objects.

JS references variable declarations and assignments of data types

Non-primitive JS data types behave differently than primitive JS data types.

Let’s start with a simple example.
Below, we declare a variable named “myArray” and initialize it with an empty array.

let myArray = []Copy the code

This happens in memory when you declare the variable “myArray” and assign it a non-primitive data type (such as “[]”) :

  1. Create a unique identifier for the variable (” myArray “).

  2. Allocates an address in memory (to be allocated at run time).

  3. The value of the memory address allocated on the heap (to be allocated at run time) is stored.

  4. Memory addresses on the heap store allocated values (empty arrays []).





From here, we can call push

,

popOr whatever we want to do.

myArray.push("first")myArray.push("second")myArray.push("third")myArray.push("fourth")myArray.pop()Copy the code


let  vs. const

Usually, we should
As much as possible
The use of
const
, and only
When we know that the variable is going toTo change the
When using
let
.

Let’s really get this straight
“Change”The meaning of.

One misconception is that
“Change”Refers to the
“Change”The value of the variable,
Describe the “change” behavior in code:

let sum = 0
sum = 1 + 2 + 3 + 4 + 5

let numbers = []
numbers.push(1)
numbers.push(2)
numbers.push(3)
numbers.push(4)
numbers.push(5)
Copy the code

The program uses
let 
That’s correct“Sum”
Because they know it’s going to change.
use
let 

The statement

numbers

, the call
push 
Change its value.

Now let’s explain what “change” means

let

You can change the memory address.

const

You are not allowed to change memory addresses.

const importantID = 489importantID = 100 // TypeError: Assignment to constant variableCopy the code

Let’s imagine what’s happening here.

When “mportantID” is declared, a memory address is allocated and the value 489 is stored.
Remember to treat the variable “importantID” as equal to the memory address.



When 100 is assigned to “importantID,” a new memory address is allocated and the value of 100 is stored there, since 100 is the basic data type.
JS then tries to assign the new memory address to “importantID”, which is where the error is raised.




When you assign 100 to ImportantID, you are actually trying to allocate a new memory address to store 100.
This is not allowed because ImportantID is declared as const.

As mentioned above, JS is assumed to be used by novices
let 
Their arrays were incorrectly declared
.

Instead, they should
const 
It is declared
.

This may seem confusing at first.
I admit, it’s not intuitive at all.
A beginner would think that the array is only useful to us if we can change it, while
const 
Make the array
Cannot be changed

So why use it?
But remember:
“Changes” are defined by memory addresses.
Let’s dig a little deeper into why it is perfectly possible and preferred to declare an array using const.

const myArray = []Copy the code

When myArray is declared, a memory address is allocated on the call stack, and the value is the memory address allocated on the heap.
The values stored in the heap are the actual empty arrays.
Visualization, which looks like this:





If we’re going to do this…

myArray.push(1)
myArray.push(2)
myArray.push(3)
myArray.push(4)
myArray.push(5)Copy the code


This pushes the number into an array that exists in the heap.
However,
The memory address of myArray is not changed.
This is why, despite declaring “myArray” with constants, no errors are raised.
“MyArray” is still equal to “0458AFCZX91”, whose value is another memory address “22VVCX011”, whose value is the value of the array on the heap.

An error is raised if you do:

myArray = 3Copy the code

Since 3 is the basic data type, we will allocate a memory address on the call stack and store the value 3, and then we will try to assign the new memory address to myArray.
But since myArray is declared as const, this is not allowed.



Another example that will raise an error:

myArray = ['a']Copy the code

Due to the
['a']Is a new non-primitive array, so a new memory address is allocated on the call stack and the value of a memory address on the heap is stored, and the value stored on the heap memory address will be [‘ of ‘].
We will then try to assign the call stack memory address to myArray, which will raise an error.



For use
const 
Declared object

Since objects are not basic data types, you can add keys, update values, and so on.

const myObj = {} 
myObj['newKey'] ='someValue'// This will not raise an errorCopy the code

Why does this work for us

JavaScript is the number one programming language in the world (according to
GitHub 
and

Stack Overflow’s annual developer survey


).
Developing mastery and becoming “JS Ninja” is something we all aspire to be.
Any decent JS course or book advocated
const 
and
let
va r
To give up
But they don’t have to say why.
For some beginners, why some
const

Variables in
“Change”Its value throws an error while other variables
It doesn’t. It’s not intuitive
.
For me, why do these programmers then default
Here and there
use
let 
To avoid trouble
It makes sense
.

However, this is not recommended.
Google, which owns the world’s best encoder, says in its JavaScript programming style guide: “Use
const
or
let
Declare all local variables
.
By default, const is used unless a variable needs to be reassigned.
VAR

Keyword not recommended “(
The source
).

Although, as far as I know, they didn’t specify why, there are several reasons:

  1. Too much freedom causes bugs.

  2. Variables declared with const must be initialized at declaration time, forcing coders to be thoughtful about scope.
    This ultimately leads to better memory management and performance.
  3. Others communicate with you through your code, which variables are immutable and which can be reassigned.

I hope the above explanation helps you to begin to understand:

Const or Let

reference
:

  1. Google JS Style Guide

  2. Learning JavaScript: Through shared calls, parameter passing

  3. How JavaScript works: Memory Management + How do you handle four common memory leaks


The last

Recently I recorded several big factory written test to explain the real questions, prepare for the interview can pay attention to:

Bi li bi li 2020 campus recruitment front written paper (a) : www.bilibili.com/video/av834…

Bi li bi li 2020 campus recruiting technical pen examination paper (2) : www.bilibili.com/video/av834…

Millet in the autumn of 2019 for front-end development pen questions (B) : www.bilibili.com/video/av834…

Alibaba in the autumn of 2017 recruit front-end pen questions (last) : www.bilibili.com/video/av834…

If you like my article, you can follow my wechat official account.