javascript tutorial - [Solved-5 Solutions] Null an object - javascript - java script - javascript array



Problem:

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

Solution 1:

Is checking

if ( object == null )
      Do something
click below button to copy the code. By JavaScript tutorial team

the same as

if ( !object )
      Do something
click below button to copy the code. By JavaScript tutorial team

Solution 2:

(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

Solution 3:

alert(typeof(null));      // object
alert(typeof(undefined)); // undefined

alert(null !== undefined) //true
alert(null == undefined)  //true
click below button to copy the code. By JavaScript tutorial team

Checking

  • object == null is different to check if ( !object ) .
  • The latter is equal to ! Boolean(object), because the unary ! operator automatically cast the right operand into a Boolean.
  • Since Boolean(null) equals false then !false === true.

Solution 4:

null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object".

Solution 5:

  • property when it has no definition, is undefined. null is an object. Its type is object. null is a special value meaning "no value. undefined is not an object, it's type is undefined.
  • You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

Related Searches to javascript tutorial - null an object