Header add

In this article we will discuss What is the difference between null and undefined in JavaScript ?

Both "undefined" and "null" are the most commonly used technical terms in JavaScript. These two terms may look the same, but they are different from each other. In this article, we are going to explore what is undefined and what is null, and what are the similarities and differences between them in JavaScript.

What is undefined?

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as: "undefined" means a variable is declared, but currently no value has been assigned to it.

The type of undefined is "undefined"



Scenarios
  • Implicit returns of function due to missing return statements.

Implicit returns of function due to missing return statements
  • Find non-existent properties in the objects.

What is null?

"null" is an assignment value and it can be assigned to a variable which indicates that a variable has no value. The type of null is "object".



Similarities between undefined and null

Both undefined and null are false values. All other values are considered as truthy in JavaScript. Falsy values are,
  • null
  • undefined
  • false
  • 0
  • "" (empty string)
  • NaN (Not A Number)

Both undefined and null are primitive values. All other values are objects in JavaScript. Primitive types are,
  • Null
  • Undefined
  • Number
  • Boolean
  • String
  • Symbol

Both undefined and null are loosely equal. In JavaScript, loosely equal means only compare values between two variables which means comparing two values after converting them into a common type.

null == undefined // true 

In the above statement, null is converted to zero, and undefined is converted to NaN. Both zero and NAN are false values. So, the condition returns true.

Differences between undefined and null

Both undefined and null are strictly not equal. In JavaScript, strictly equal means compare both type and value of the two variables. Here the types of undefined and null are different (Type of undefined is "undefined " and type of null is "object").


Why first statement prints 'Test'? Because undefined means no value, that is you didn't pass any value to parameter 'str'. So, the default value 'Test' is printed.
Why second statement prints 'null'? Because null is assignment value which means you are passing and assign null value to parameter 'str'. So, 'null' is printed.

Summary

undefined means variable has been declared but not yet assigned with any value. The type of undefined is "undefined".
null is an assignment value that means nothing. The type of null is "object".

Both undefined and null are falsy and primitive values.
null == undefined is true, but null === undefined is false.

Post a Comment

Previous Post Next Post