Data type of JavaScript and its detection


1、 How many types of values does JavaScript have?

JavaScript has two data types: basic data type and reference data type. The basic data types include undefined, null, Boolean, number, string and symbol (added in ES6 to represent unique values), while the reference data types are collectively referred to as object objects, mainly including objects, arrays and functions. Next, let’s look at the characteristics of the two.

2、 Basic data type

1. The value is immutable

var name = 'java';
name.toUpperCase(); //  Output 'Java'
console.log(name); //  Output 'Java'

Thus, the value of the basic data type cannot be changed

2. Store in stack area

The original data type is a simple data segment directly stored in the stack. It occupies a small space and has a fixed size. It is frequently used data, so it is stored in the stack.

3. Comparison of values

var a = 1;
var b = true;
console.log(a == b);    // true
console.log(a === b);   // false

==: only value comparison and data type conversion are performed.
===: compare not only the values, but also the data types.

3、 Reference data type

1. The value is variable

var a={age:20};

The above code shows that reference types can have properties and methods, and can be changed dynamically.

2. Save in stack memory and heap memory at the same time

Objects with reference data types stored in the heap occupy a large space and are not fixed in size. If they are stored in the stack, they will affect the performance of the program; The reference data type stores a pointer in the stack that points to the starting address of the entity in the heap.When the interpreter looks for a reference value, it will first retrieve its address in the stack, and then obtain the entity from the heap.

3. Comparison is the comparison of references

When a reference type value is assigned from one variable to another, the value of the object stored in the variable will also be copied and placed in the space allocated for the new variable.

var a={age:20};
var b=a;

As mentioned above, the location of basic types and reference types stored in memory is different. Reference types are stored in objects in the heap. At the same time, pointers are stored in the stack, and this pointer points to the starting location of entities in the heap. When variable a is initialized, a pointer points to the address of the object {age: 20}. After a is assigned to B, B points to the address of the object {age: 20}. These two variables point to the same object. Therefore, changing any of these variables will affect each other.

At this time, if you cancel the reference of a variable to the original object, it will not affect another variable.

var a={age:20};
var b=a;
a = 1;
b // {age:20}

In the above code, a and B point to the same object, and then the value of a becomes 1. At this time, it will not affect B, and B still points to the original object.

4、 Inspection data type


Typeof returns a string representing the data type, the returned results include 7 data types: number, Boolean, string, symbol, object, undefined and function, but null and array cannot be judged

typeof Symbol(); //  Symbol valid
typeof ''; //  String valid
typeof 1; //  Number is valid
typeof true; // Boolean valid
typeof undefined; // Undefined valid
typeof new Function(); //  Function valid
typeof null; // Invalid object
typeof [] ; // Invalid object
typeof new Date(); // Invalid object
typeof new RegExp(); // Invalid object

Both arrays and objects return objects. In this case, you need to use instanceof to judge


Instanceof is used to judge whether a is an instance of B. the expression is: a instanceof B. If a is an instance of B, it returns true; otherwise, it returns false.The instanceof operator is used to test whether an object has the prototype attribute of a constructor in its prototype chain.

[] instanceof Array; //true
{} instanceof Object;//true
new Date() instanceof Date;//true
new RegExp() instanceof RegExp//true

For the type judgment of array, you can also add it with ES6Array.isArray()

Array.isArray([]);   // true

Three disadvantages of instanceof

  • For basic data types, the results created by literal method are different from those created by instance method
console.log(1 instanceof Number)//false
console.log(new Number(1) instanceof Number)//true

Strictly speaking, only the result created by the instance is the standard object data type value, and it is also an instance of the standard number class; The result created by literal method is a basic data type value, not a rigorous instance. However, due to the loose characteristics of JS, the method provided on number.prototype can be used.

  • As long as it is on the prototype chain of the current instance, the result detected by it is true.In the prototype inheritance of classes, the results we finally detect may not be accurate
var arr = [1, 2, 3];
console.log(arr instanceof Array) // true
console.log(arr instanceof Object);  // true
function fn(){}
console.log(fn instanceof Function)// true
console.log(fn instanceof Object)// true
  • Null and undefined cannot be detected

For special data types null and undefined, their classes are null and undefined, but the browser protects these two classes and does not allow us to access and use them outside


The role of constructor is very similar to that of instanceof.However, unlike instanceof, the constructor can also handle the detection of basic data types.

var aa=[1,2];
var reg=/^$/;

Two disadvantages of constructor

  • Null and undefined are invalid objects, so there will be no constructor. These two types of data need to be judged in other ways.

  • The constructor of the function is unstable. This is mainly reflected in rewriting the prototype of the class. In the process of rewriting, it is likely to overwrite the previous constructor. In this way, the detected results are inaccurate

function Fn(){}
Fn.prototype = new Array()
var f = new Fn

Object. Prototype. ToString. Call() is the most accurate and commonly used method。 First, get the toString method on the object prototype, let the method execute, and let this in the toString method point to the value of the first parameter.

Important supplementary notes on toString

  • It is intended to be converted to a string, but some toString methods are not just converted to a string
  • For number, string, Boolean, array, regexp, date and function prototypes, toString methods convert the current data type to string type (they are only used to convert to string)
  • ToString on object is not used to convert to string.

ToString on object is used to return the details of the class of the main body (this in the method) executing the current method, that is “[object object]”, where the first object represents that the current instance is of object data type (this is fixed), and the second object represents that this belongs to object.'') ;   // [object String] ;    // [object Number] ; // [object Boolean] ; // [object Undefined] ; // [object Null] Function()) ; // [object Function] Date()) ; // [object Date][]) ; // [object Array] RegExp()) ; // [object RegExp] Error()) ; // [object Error] ; // [object HTMLDocument] ; // [object global] window is a reference to the global object global

Author: boating in the waves
Link:Data type of JavaScript and its detection
Source: GitHub
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.