Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is null an object and what's the difference between null and undefined?

Why is null considered an object in JavaScript?

Is checking

if ( object == null )       Do something 

the same as

if ( !object )       Do something 

?

And also:

What is the difference between null and undefined?

like image 420
rahul Avatar asked Apr 29 '09 05:04

rahul


People also ask

What's the difference between null and undefined?

Difference Between undefined and nullundefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.

Why is null an object?

The concept of nullnull is a primitive value that represents the intentional absence of any object value. If you see null (either assigned to a variable or returned by a function), then at that place should have been an object, but for some reason, an object wasn't created.

Why is null == undefined true?

The == comparison operator doesn't check the types. null and undefined both return false . That's why your code is actually checking if false is equal to false . However their types are not equal.


1 Answers

(name is undefined) 

You: What is name? (*)
JavaScript: name? What's a name? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?

name = null; 

You: What is name?
JavaScript: I don't know.

In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.

One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, i.e.

name = false; 

You: What is name?
JavaScript: Boolean false.

name = ''; 

You: What is name?
JavaScript: Empty string


*: name in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.

like image 97
Rob Avatar answered Oct 18 '22 18:10

Rob