The introduction

In daily work, in the front of the us, ever-present in the variable declaration and assignment, whether you have come across variable declarations, an error or variable polluted problem, if you like the author met, then we should temporarily stop to think about the cause of the problem and how to take appropriate remedial measures. Of course, the best way to troubleshoot a problem is to go into the underlying details and understand how memory is allocated in JavaScript. The problems we encounter in writing code can be easily solved only when we have a good understanding of the underlying details. This article’s javascripts based memory model continues to derive differences between lets and const. Please point out any errors in this article.

1. What is memory

Before we get into the memory model in JavaScript, let’s take a quick look at what memory is at the hardware level.

Memory is one of the most important parts in computer. It is the bridge between external memory and CPU. All programs in a computer are run in memory, so the performance of memory has a great impact on the computer. Memory, also known as internal Memory and main Memory, is used to temporarily store computational data in the CPU and data exchanged with external Memory such as hard disk. As long as the computer is running, the CPU will transfer the data to the memory for operation. When the operation is completed, the CPU will transmit the results. The operation of the memory also determines the stable operation of the computer.

A memory chip is a key part of a computer’s architecture. It is itself a very sophisticated component, containing hundreds of millions of electronic components, which are tiny at the nanoscale. The voltage of the circuit changes, but there are only two possibilities, either 0V(low level) or 5V(high level). 0V is power off, represented by 0, and 5V is power on, represented by 1. Therefore, a component contains two states, 0 and 1, representing a bit. But as humans, we’re not very good at using bits to think and calculate, so we divide them into larger groups, such as 8 bits for 1 byte, 16 bits for 2 bytes, and 32 bits for 4 bytes. Many things are stored in memory, such as our program code, variables declared in the program, and operating system code.

2. Memory life cycle

With the basic concepts of memory behind us, let’s talk briefly about the memory life cycle. JavaScript as a high-level programming language, unlike other languages (such as C) where developers have to manage memory manually, the system allocates memory for you automatically. But regardless of programming language, the memory life cycle is divided into three main phases:

  • Allocate memoryMemory is allocated by the operating system for use by programs. In JavaScript, this step is automatically assigned by the operating system without the developer having to do it manually.
  • The use of memory: After a program obtains memory allocated by the operating system, read and write operations occur in memory.
  • Free memoryWhen a program finishes using the memory, it frees it up for other programs to use. In JavaScript, this step is also released automatically by the operating system without requiring the developer to do it manually.

As we know, data types in JavaScript are divided into basic data types and reference data types. The basic data types include String, Number, Boolean, Null, Undefined, Symbol in ES6, and BigInt. Others are reference data types, such as Array, Date, Function, RegExp, Error, Object, etc. One of the differences between the two data types is that the memory size of the base data type is fixed, while the memory size of the reference data type is dynamically variable and can change over time. Therefore, there will be some differences between the two data types during the memory allocation phase.

Compiler when compiling code for basic data types, because of its size is fixed, the compiler checks to calculate in advance when they need memory size, and insert interact with the operating system code, apply to the operating system storage variable required bytes of the stack, then will apply to the memory allocated to the call stack in the program, called a static memory allocation. For example, when a function is called, the memory required for variables in the function is added to the existing memory, which is removed in LIFO order when the function is completed. But for reference data types, its size is dynamic, the compilation phase cannot directly determine its need to how much memory, therefore could not allocate memory on the stack for it, on the contrary, need to apply to the operating system for the proper memory at run time, and this part of the memory is allocated on the heap space, called dynamic memory allocation. The differences between static and dynamic memory allocation are shown in the following table:

Static memory allocation Dynamic memory allocation
The compile phase determines the size The size cannot be determined at compile time
Execute at compile time Execute at runtime
Assign to stack Assigned to a pile of
Sequential allocation, last in first out (LIFO) Disordered distribution

Memory allocation in JavaScript

Development, in the front of the our daily work, almost every day doing the declaration and assignment of variables, these variables will eventually be stored into the memory, so we still have a need to know about the memory allocation methods in JavaScript, here use basic data types, and reference data types to address the memory allocation process, Helps us understand the low-level details of JavaScript. We’ll start with a simple assignment to a primitive data type, as follows:

let num = 1;
Copy the code

When the JavaScript engine executes this line of code, it does something like this:

  • As a variablenumCreates a unique identifier for the address in stack memoryA1Form a mapping relationship.
  • Assign it an address in stack memoryA1.
  • The value1Store to the assigned address.

Here’s an example:

num
1
num
A1
newNum
num

let newNum = num;
Copy the code

After the above assignment, it is usually said that the value of newNum is 1, which also strictly means that newNum and num refer to the same memory address A1, as shown in the following figure:

num = num + 1;
Copy the code

We increment the num variable, which obviously has a value of 2. The value of “newNum” and “num” refers to the same memory address A1.

num
A1
A2
Basic data types are immutable
newNum
1

let str = 'ab';
str = str + 'c';
Copy the code

Since strings are also basic data types, which are immutable, even if the above code simply concatenates C to the original string AB, it will still be assigned a new memory address. The variable STR will eventually refer to the new memory address, as shown in the following figure:

let arr = [];
Copy the code

When the JavaScript engine executes this line of code, it does something like this:

  • As a variablearrCreates a unique identifier for the address in stack memoryA3Form a mapping relationship.
  • Assign it an address in stack memoryA3.
  • Stack memory Stores the value of the memory address allocated in the heapH1.
  • Stores allocated values in the heapAn empty array [].

Here’s an example:

JavaScript engines (such as Chrome’s and Node’s V8 engines) are made up of two main components, the Memory Heap and the Call Stack.

4,letandconstDifference contrast of

After understanding of the memory allocation mode of the above two types of data, we are here to let the comparison and the use of the const way, generally speaking, we suggest that can use in the process of writing code const decrease as far as possible using the let, so that we can to some extent avoid variable is modified by a series of problems. The following code:

let num = 1;
num = num + 1;
let arr = [];
arr.push(1);
arr.push(2);
arr.push(3);
Copy the code

In the code above, the num variable is allowed to be modified because it is declared in let mode, and since the values of primitive types are immutable, a new memory address is assigned to the num variable. For arR variables, let declaration is also used to indicate that it is allowed to change. However, for push operations, the memory address of ARR variables is not changed, but the new value is pushed into the array of heap memory. Therefore, it is recommended to change the declaration to const.

If the memory address is allowed to change, it is declared using let, otherwise it is declared using const.

The following is an example:

const num = 1;
num = num + 1;
Copy the code

From the memory allocation for the basic data types we learned in the previous section, we know that the variable num is allocated an address in stack memory to hold the corresponding value.

const
num

const arr = [];
Copy the code

For reference data types, we know that memory addresses are allocated to them on the stack, and the value of the memory address in the heap is stored.

arr.push(1);
arr.push(2);
arr.push(3);
Copy the code

push
const

arr = 1;
arr = undefined;
arr = null;
arr = [];
arr = {};
Copy the code

All of these methods modify the memory address of the original array. A const declaration is not allowed to modify the memory address, so it obviously throws an error. Therefore, it is recommended that const variables be declared by default, unless the memory address needs to be changed. Variables declared by const must be initialized at declaration time, so that other front-end personnel can see at a glance which variables are immutable.

5, summary

In this article, we mainly summarize the memory model in JavaScript, and describe the memory allocation method in JavaScript respectively for basic data types and reference data types. Then we compare let and const variable declaration methods in code to understand the differences. The next part will continue to explain the garbage collection mechanism in JavaScript engine based on the memory model, and several effective ways to avoid memory leaks in the process of writing code, with you to understand the low-level details of JavaScript.

6, communication

If you feel that the author’s article is helpful to you, might as well pay attention to the author’s public number, every week will be original and sort out some front-end technology dry goods, after paying attention to the public number can invite you into the group, we communicate with the front end, learn from each other, and make progress together.

The article has been updated toMaking a blog, if your article is ok, welcome to STAR!

One of your likes is worth more effort!

Grow up in adversity, only continue to learn, to become a better yourself, with you!