How to Check Data Types in JS?

I. Check undeclared, undefined or null

  1. undeclared check: try-catch-finally

    1
    2
    3
    4
    5
    6
    7
    8
    try{
    var; // must use it here (in any way)
    }
    catch(e) {
    if(e.name === 'ReferenceError') {
    console.log('var is undeclared')
    }
    }
  2. undefined check: typeof var

    1
    2
    3
    4
    5
    var undefinedVar

    if (typeof undefinedVar === 'undefined') {
    console.log('var is undefined')
    }
  3. null check: if(var===null)

    1
    2
    3
    4
    5
    var nullVar = null

    if (nullVar === null) {
    console.log('var is null')
    }

II. String

  1. Three ways to generate String

    • String: let var = '1'
    • String: let var = String(1)
    • [object String]: let var = new String(1)
  2. How to check - [ primitive string & String object ]

    1
    2
    3
    // primitive string
    // String object
    if (typeof var === 'string' || var instanceof String)

III. Number

  1. Check a Number

    1
    2
    3
    4
    // primitive string
    // String object
    // Must not `NaN`
    if ( typeof var === 'number' || value instanceof var ) && isFinite(var) )
  2. 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
2
3
4
// Returns if a value is a function
function isFunction (var) {
return typeof var === 'function';
}

VI. Boolean

1
2
3
4
// Returns if a value is a boolean
function isBoolean (var) {
return typeof var === 'boolean';
}