-2

I have a scenario where function only gets one argument which could be either object or null. As both object and null has type of object. How can I use if statement on them to differentiate? If I use typeof then both object and null will return object.

UPDATE

function func (par) {
    if (par === null) {
        console.log(null);
    }

    if (typeof par === "object") {
        console.log(object);
    }
}

func({key1: 'val1', key2: 'val2'});
func(null);
Om3ga
  • 30,465
  • 43
  • 141
  • 221
  • 1
    Does `=== null` not work? – helion3 Feb 20 '14 at 20:31
  • I don't understand the problem. You're checking for null value and then you're checking the type to see if it's an object. Isn't that what you intended to do? – CatDadCode Feb 20 '14 at 20:39
  • null is not an object, it is a primitive value. check this page : [link] http://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-between-null-and-undefined – vahid Feb 20 '14 at 20:42
  • @AlexFord No because the second condition is true for both `object` and `null`. – Om3ga Feb 20 '14 at 20:44

2 Answers2

6

You can just check if the argument is null:

UPDATED (per change in problem definition)

if(arg === null)

function func (par) {
    if (par === null) {
        console.log(null);
    } else if(typeof par === "object") {
        console.log(par);
    } else {
        console.log("Unexpected parameter");
    }
}

func({width: '1px', color: 'orange'});
func(null);
Rob M.
  • 35,491
  • 6
  • 51
  • 50
1

If you need to know if it is null OR of type object then simply make the second if an else if.

function func (par) {
    if (par === null) {
        console.log(null);
    } else if (typeof par === "object") {
        console.log(object);
    }
}

func({key1: 'val1', key2: 'val2'});
func(null);

http://codepen.io/Chevex/pen/GbKeg

CatDadCode
  • 58,507
  • 61
  • 212
  • 318
  • Is there any other solution? I mean better one. – Om3ga Feb 20 '14 at 20:47
  • lol, what does that even mean? Better how? If you *have* to know that `par` is an object then there is no better way to check that. If you don't *have* to know what the type is after you know it's not `null` then you can just use a simple `else` instead of `else if`. Other than that I don't know what else to tell you. – CatDadCode Feb 20 '14 at 21:02