I. Check undeclared
, undefined
or null
undeclared
check:try-catch-finally
1
2
3
4
5
6
7
8try{
var; // must use it here (in any way)
}
catch(e) {
if(e.name === 'ReferenceError') {
console.log('var is undeclared')
}
}undefined
check:typeof var
1
2
3
4
5var undefinedVar
if (typeof undefinedVar === 'undefined') {
console.log('var is undefined')
}null
check:if(var===null)
1
2
3
4
5var nullVar = null
if (nullVar === null) {
console.log('var is null')
}
II. String
Three ways to generate String
- String:
let var = '1'
- String:
let var = String(1)
- [object String]:
let var = new String(1)
- String:
How to check - [ primitive string & String object ]
1
2
3// primitive string
// String object
if (typeof var === 'string' || var instanceof String)
III. Number
Check a Number
1
2
3
4// primitive string
// String object
// Must not `NaN`
if ( typeof var === 'number' || value instanceof var ) && isFinite(var) )Check
NaN
1
2
3
4
5// 1. return true for all non-number
isNaN(var)
// 2. only return true for exact 'NaN'
Number.isNaN(var)
IV. Array
1 | Array.isArray(var); |
V. Function
1 | // Returns if a value is a function |
VI. Boolean
1 | // Returns if a value is a boolean |