I read js you Don’t Know today. I can’t remember exactly what typeof returns are. Make a note of it.
The Typeof operator returns type information as a string. We can use typeof to find out if a variable exists, such as if(typeof a! =”undefined”){}, do not use if(a) because if a does not exist (undeclared), typeof returns object for special objects such as Array,Null, etc. This is the limitation of Typeof.
Return value of typeof
Typeof has six possible return values:
- ‘String’ – a variable or value of type string
- ‘undefined’ — undefined variable or value
- ‘BOOLen’ – Boolean type variable or value
- ‘number’- variable or value of type number
- ‘object’ – variable or value of object type, or NULL,Array
- ‘function’- a variable or value of function type
example
console.log('1'.typeof 'aixoaxue')
console.log('2'.typeof undefined)
console.log('3'.typeof true)
console.log('4'.typeof 23)
console.log('5'.typeof {a:'45'})
console.log('6'.typeof function () {})Copy the code
In total, Typeof returns six types; For object, instanceof is needed for further judgment