Jimmy Cuadra Jimmy Cuadra - 1 year ago 107
Javascript Question

What reason is there to use null instead of undefined in JavaScript?

I've been writing JavaScript for quite a long time now, and I have never had a reason to use

. It seems that
is always preferable and serves the same purpose programmatically. What are some practical reasons to use
instead of

Answer Source

Null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.

That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.

Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simiplifies things a lot. I never have to check if x === undefined || x === null. And if you're in the habit of using == or simply stuff like if(x) ... . Stop it. !x will evaluate to true for an empty string, 0, null, NaN - ie things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download