Javascript Object Prototype Check null value

Description

Javascript Object Prototype Check null value


// Rewriting our improved typeof to stand as a static function and test for null
Object.getType = function(obj) {
    if (typeof(obj) == "object") {
        if (obj === null) return "null";
        if (obj.constructor == (new Array).constructor) return "array";
        if (obj.constructor == (new Date).constructor) return "date";
        if (obj.constructor == (new RegExp).constructor) return "regex";
        return "object";
    }/*w  ww.j  av  a  2s .c om*/
    return typeof(obj);  
}

// Testing our static getType() function
let myArray = new Array();
let myObj = new Object();
let myRegex = new RegExp();
let myDate = new Date();
let myNull = null;

console.log(Object.getType(myArray));    // "array"
console.log(Object.getType(myObj));    // "object"
console.log(Object.getType(myRegex));    // "regex"
console.log(Object.getType(myDate));    // "date"
console.log(Object.getType(myNull));    // "null"



PreviousNext

Related