1. Simple data types

Simple types (basic data types, value types) : The value itself is stored in the variable during storage, including String, number, Boolean, undefined, null

2. Complex data types

Complex data types (reference types) : Only addresses (references) are stored in variables during storage. Objects (system objects, custom objects) created by the new keyword, such as Object, Array, Date, etc.

3. The stack

3.1. Stack space allocation differences:

1. Stack (operating system) : the operating system automatically distributes and releases the parameter values and local variable values of the storage function. It operates like a stack in a data structure;

Simple data types are stored on a stack

2, heap (operating system) : store complex types (objects), generally allocated by the programmer to release, if the programmer does not release, by the garbage collection mechanism to recover.

Complex data types are stored in the heap

Note: There is no concept of a stack in JavaScript, which makes it easier for you to understand some of the ways code is executed and to learn other languages in the future.

3.2. Storage of simple data types

The data of a value type variable is stored directly in the variable (stack space)

3.3. Storage methods for complex data types

Reference type variables (stack space) store addresses, and real object instances are stored in heap space

4. Simple type parameter transmission

A function parameter can also be considered a variable. When we pass a value variable as a parameter to a function parameter, we are actually copying the value of the variable in the stack space to the parameter, so that any changes made to the parameter inside the method will not affect the external variable.

function fn(a) { a++; console.log(a); } var x = 10; fn(x); The console. The log (x);Copy the code

The running results are as follows:

5. Parameter transmission for complex data types

A parameter of a function can also be treated as a variable. When we pass a reference to a type variable to a parameter, we are actually copying the stack address of the variable to the parameter. The parameter and the argument actually hold the same heap address, so we operate on the same object.

function Person(name) { this.name = name; } function f1(x) { // x = p console.log(x.name); // 2. What is this output? X. name = "Jacky Cheung "; console.log(x.name); // 3. What is this output? } var p = new Person(" Andy lau "); console.log(p.name); // 1. What is this output? f1(p); console.log(p.name); // 4. What is this output?Copy the code

The running results are as follows: