This is the fifth day of my participation in the August Wen Challenge.More challenges in August !

Starting with an interview question, what are the data types of JS? How do you determine the data types and the strengths and weaknesses of each approach

Js data type

  • Basic data types: String, Number, Boolean, Null, Undefined, Symbol

    Symbol is ES6’s introduction of a new primitive data type that represents unique values

  • Reference data types: Object, Array, Function

Array type determination method

  • (1). Typeof:

    Typeof is an operator that can be used in two ways: typeof(expressions) and Typeof variable names, the first to operate on expressions and the second to operate on variables

    The typeof operator returns a string of the following values:

'Boolean' -- Boolean variable or value 3. 'string' -- string variable or value 4. 'number' -- numeric variable or value 5. 'object' 6. 'function' -- a variable or value of a function typeCopy the code

For basic data types, all but null returns object. The correct type is applicable to base types, reference types, and all but function returns object

  • (2).instanceof

    Instanceof can only be used to determine whether the prototype chain of a variable has a constructor’s prototype attribute (whether two objects belong to the prototype chain). Instanceof may not be used to determine the specific type of the object

  • (3).constructor

    Each instance object can access its constructor via constructor, which is also based on the principle of prototype chain. Since undefined and NULL are invalid objects and therefore have no constructor attribute, these two values cannot be determined in this way

  • (4)Object.prototype.toString.call

Extension: why Object. The toString () and the result of the Object. The prototype. ToString. The result of the call (obj) different?

This is because toString is a prototype method of Object, while Array, Function, and other types, as instances of Object, override toString. When the toString method is called by different object types, the corresponding overridden toString method is called based on the knowledge of the prototype chain (Function returns a string containing the body of a Function, Array returns a string consisting of elements…..). ToString () does not get its Object type. Instead, it can only convert obj to a string. Therefore, when you want to get the concrete type of an Object, you should call the prototype toString method on Object

Conclusion:

Null and object instanceof can also be used to detect native objects, failing between different iframes and Windows. Note also that object.create (null) constructor can judge almost all types except null and undefined, but constructor can be easily modified, and toString cannot judge all types across iframes. It can be encapsulated as an all-powerful DataType() that determines all data types