[Difference between value type and reference type]

The difference between value types and reference types

  • Variables in js are divided into two types: value type (basic data type) and reference type

    • Value types: string, number, boolean, null, undefined, and symbol types

    • Reference types: Object (object), Array (array) and Function (function)

  • The difference between value types and reference types:

    1. Variables are stored differently:

      When we declare a variable, the variable is stored in the memory in the form of key-value, and the memory has stack memory and heap memory.

      Value types and reference types are stored in different ways in memory. Variables of value type are stored in stack memory, key stores the name of the variable, and value stores the value of the variable. For example, declare the variable let a = 100, It is stored in stack memory like this:

insert image description here
The storage method of reference type variables is more complicated than that of value types. For example, when declaring a variable of object type, the javascript virtual machine will open up a space in both the stack memory and the heap memory, and store the value of the variable in the heap memory. , the variable name is stored in the key of the stack memory, and the value in the stack memory is stored in the memory address, which points to the address of the heap memory to store the object content.
insert image description here
2. The copying method is different:
The value type copies the value of the variable when copying, the new variables and the original variables are independent and do not interfere with each other.
insert image description here
The reference type is a shallow copy, and the copy is the reference address, so the new variable and the original variable point to the same object. When one of the variables modifies the content of the object, the other variable will also change. '
insert image description here

  1. Compare differently:

    The comparison of value types is the comparison of values. When comparing their values, they are equal. When comparing, pay attention to == and ===. When using == for comparison, type conversion is performed. When the values ​​​​of variables are equal, they are regarded as Equality, and when using === (congruent equality) to compare, it will compare whether the value and type are equal, and it is only equal when both the value and type are equal.

    Reference types compare reference addresses, even if the properties and values ​​of two objects are exactly the same, they are not necessarily equal.

Guess you like

Origin blog.csdn.net/m0_37873510/article/details/126363794