This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact.

Accompanying video tutorial address

Bilibili: The nature of the Difference between JS basic types and reference types

Front knowledge

Weak and strong types

Js is itself a weakly typed language. Here weak, have weakened, desalinate the meaning. Whether a variable is declared using var or let, no type is specified for the variable.

withjavaThe contrast of

When you declare a variable in Java, you need to specify the type of the variable. Therefore, when you declare a variable in Java, you specify that it must contain the specified type. If you assign another type of data, an error will be reported.

public class Test {
    public static void main(String[] args) {
		int a = 1;
		a = 'abc'; // The data type of the variable cannot be changedSystem.out.println(a); }}// More statements to declare variables
String str = "Hello"; // Declare and initialize the variable STR as a string
double pi = 3.1415926; // Declare and initialize the variable PI as a double-precision floating point type
char c = 'c';        // Declare and initialize variable c with a value of the 'c' character type
Copy the code

As shown in the above code, the type of variable A is specified as an integer when declaring variable A. Assigning a string to variable A of an integer will cause an error.

There are also three Java variable types listed below. In Java, variables can be declared using keyword classes such as int, String, double, char, etc., so there are types of variables in Java. So Java is strongly typed.

Static versus dynamic typing

Java is a statically typed language because variable types are relatively quiet and easily unchangeable.

In JS, the declaration of variables does not specify the type at all, and there is no limit to change the data type stored in variables, can be changed at any time, so JS belongs to dynamic type language.

Differences in code writing

Due to the difference of strong and weak or static language types, there are also great differences in coding.

Because statically typed languages are more strict about variable types, developers have to pay more attention to the syntax, and the benefit is that you can avoid many of the problems associated with data types during development. Because the variable type is fixed, the development tool (IDE) can give a good intelligent code prompt and detect the variable type error in the code at the writing stage. This makes the code more standard and secure.

Contrast, dynamically typed languages in the coding phase can put more focus on business logic, because the type is not fixed, so write the code more flexible, but development tools (IDE) is also unable to better detection code, thus inevitably hiding some didn’t pay attention to the problems associated with variable type, may be can only be found by testing, So the code specification is not as good as statically typed languages.

Variable types and data types

Variable types

Js variables themselves are not typed. What we often refer to as a variable type is actually the type of value that is stored in the variable.

Primitive and reference types

Since the variable has no type in JS, and the type of the variable depends on the type of the data stored inside, so whether the variable saves the data itself or just a reference to the address of the data in the heap memory can be generally divided into the following two types:

  • Primitive Type (Primitive Value)
    • Save the data itself, and the data is stored in stack memory
    • Such as values, strings, and Booleans
  • Reference value
    • The data itself is stored in heap memory, and the stack memory is just the address of the data
    • Object types such as functions, arrays, native objects, etc
What is stack and heap

There are two main parts of memory we need to know, one is called stack memory and the other is called heap memory, so let’s look at the differences between the two

  • Stack memory
    • Is the system set up a good contiguous memory area, so the space is small, but read faster
  • Heap memory
    • Is a discontinuous memory area, the acquisition space is relatively flexible, so the space is large, but the reading speed is slow

Due to the above characteristics of stack and heap address space, the stack memory is generally used to store the original type of data that occupies a small space, while the heap memory is used to store the reference type of data that occupies a large space, and only the address of the reference type data in the heap memory is stored in the stack memory.

The data type

  • Basic types of
    • Such as values, strings, and Booleans
  • Object type
    • Object types such as functions, arrays, native objects, etc

Call typeof functions to see the return type, which is either object type, or the basic typeof number, string, Boolean, etc.

// Basic type
cosole.log(typeof 1)
// "number"
cosole.log(typeof 'a')
// "string"
cosole.log(typeof true)
// "boolean"

// Object type
cosole.log(typeof [])
// "object"
cosole.log(typeof {})
// "object"
Copy the code

The differences

Now that you know how the two types of data or variables are stored, let’s look at the differences in the code. It is important to note that assigning a value from one variable to another involves copying the contents of one variable to the other. The concern is whether the contents of the variable are the actual data or the address of the actual data.

Basic types of data transfer

var n1 = 1;
var n2 = n1;
n1 = 2;
console.log(n1);
console.log(n2); 
Copy the code

Results:

> 2
> 1
Copy the code

If n1’s true value 1 is copied and assigned to N2, there is no relationship between the two. Therefore, n2’s change has nothing to do with N1, and n2’s result will remain unchanged.

Object type data passing

var obj1 = {
  name: 'xiaoming'
}
var obj2 = obj1;
obj1.name = 'xiaohua';
console.log(obj1.name);
console.log(obj2.name);
Copy the code

Results:

> xiaohua
> xiaohua
Copy the code

For object types, we’re passing the heap address of the object in obj1, and when assigned to obj2, they both point to the heap address of the same object, through the object. The form of attribute is to find the real data of the object through the heap memory address first, and then find the value of the name attribute. It can be seen that the real data of the same object is changed, so it will affect the other one.

Reassign obj1

var obj1 = {
    name: 'xiaoming'
}
var obj2 = obj1;
obj1 = {
    name: 'xiaohua'
}
console.log(obj1.name);
console.log(obj2.name);
Copy the code

Results:

> xiaohua
> xiaoming
Copy the code

Now the result, and why? Note that obj1 has been reassigned, rather than looking up the previous address in obj1.name. This reassignment will cause the system to create a new memory space for obj1, so that obj1 and obj2 are no longer related.

Let’s do another one that’s a little more subtle

var obj = {
  name: 'xiaoming'
}
function fn(obj){
  obj.name = 'xiaohua'
}
fn(obj);
console.log(obj.name);
Copy the code

Results:

> xiaohua
Copy the code

Why is that? Why can a local variable inside a function affect a global variable outside the function? Here we know that fn does pass the global variable obj to the function as an argument, and the function also receives it as an argument obj.

Note, however, that there is actually an assignment when the function receives an argument: the local formal parameter obj is equal to the global actual parameter obj, but the two variables have the same name, so this assignment is easily ignored.

Because this is also copying the data stored in the global variable to the local variable obj inside the function, but because it is object type data, it is copying the address of the object in the heap, so obj inside the function gets the property name by point, which is the name property of the same object.

What if it’s a basic type of data

var a = 'a';
function fn(a) {
  a = 'aa';
}
fn(a);
console.log(a);
Copy the code

Results:

> a
Copy the code

The only difference here is that the real data is being copied and assigned to the local variable A. It is this assignment that separates the internal local variable from the external global variable, so that whatever the local variable does inside the function does not affect the external global variable A.

Comparison of primitive and object type values

var a = 'a';
var b = 'a';
var obj1 = {
  name: 'xiaoming'
}
var obj2 = {
  name: 'xiaoming'
}
console.log(a == b);
console.log(obj1 == obj2);
Copy the code

Results:

> true
> false
Copy the code

The only thing to note here is that since primitive data stores the value itself, two variables are equal only if they hold the same value.

Object data is stored in a variable in the heap memory address of the object, so obj1 and Obj2 hold the same contents of the object. However, since they are separate objects, such as stored in different memory locations, the comparison will not be equal.

conclusion

Ok, so that’s what I’m going to share with you about the differences in code that are caused by the way different types of data are stored. These are also easy to ignore in the peacetime development, but once you encounter problems, you will find that you really need to be able to play with ease, flexible response to various scenarios. I think, these differences can only be understood in the real practice of the true meaning of ah!