SoFunction
Updated on 2025-02-28

The best way to judge type in javascript

There are 8 data types for javascript

Value Type

  • Number
  • Null
  • Undefined
  • String
  • Symbol
  • Boolean
  • BigInt

Reference Type

  • Object
  • Array
  • Function

There are four ways to judge the data type

The first method: typeof

typeof null   ---> "object"

 typeof undefined  ---> "undefined"

 typeof true | false  ---> 'boolean'

 typeof 42    ---> 'number'

 typeof "42" ---> 'string'

 typeof { name : '1'} | []  ---> 'object'

 typeof Symbol    ---> 'symbol'

 typeof ()=>{}       ---> 'function'

 typeof void 0      ---> 'undefined'

The second method instanceof But this method is only suitable for judging object types

The instanceof operator is used to determine whether the object pointed to by the prototype attribute of a constructor exists on another prototype chain to detect the object.

For detailed introduction, please see here:instanceof operator in javascript

for example :
var arr = [] ;
arr instanceof Array   ---> true
null instanceof Object ---> false
[function] instanceof Object | Function  --> true

The third method ()  This method can detect all data types, which is also the recommended method

Because toString is the prototype method of Object, Array Function and other examples are Object instances. All rewrite the toString method. Returns a string of type

(null)  --->  [object Null]

 (undefined)  ---> [object Undefined]

 (123)  ---> [object Number]

 (true) ---> [object Boolean]

 ('123') ---> [object String]

 ({})    ---> [object Object]

 ([])    ---> [object Array]

 (Math) ---> [object Math]

 (function(){}) ---> [object Function]

 (new Date)  ---> [object Date]

 (Symbol())   ---> [object Symbol]

The fourth method: constructor: The constructor that determines the object's constructor.

1.  null yesjs The starting point of the prototype chain,No constructor

2. undefined No constructor

3. [].constructor  === Array  ---> true

4. [string].constructor === String

5. [object].constructor === object

6. [number].constructor === Number

7. [symbol].constructor === Symbol

8. [function].constructor === Function

9. [new Date].constructor === Date

10. [RegExp].constructor === RegExp

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.