Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  196] [ 7]  / answers: 1 / hits: 66751  / 13 Years ago, thu, july 7, 2011, 12:00:00

I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefined is always preferable and serves the same purpose programmatically. What are some practical reasons to use null instead of undefined?


More From » null

 Answers
12

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 simplifies things a lot. I never have to check if x === undefined || x === null, I can just check x === undefined. 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 - i.e. 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.


[#91318] Tuesday, July 5, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;