Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  34] [ 7]  / answers: 1 / hits: 67331  / 12 Years ago, tue, october 30, 2012, 12:00:00

I have seen different code examples with variables declared and set to undefined and null. Such as:



var a; // undefined - unintentional value, object of type 'undefined'
var b = null; // null - deliberate non-value, object of type 'object'


If the code to follow these declarations assigns a value to a or to b, what is the reason for using one type of declaration over another?


More From » variables

 Answers
5

The first example doesn't assign anything to the variable, so it implicitly refers to the undefined value (see 10.5 in the spec for the details). It is commonly used when declaring variables for later use. There is no need to explicitly assign anything to them before necessary.



The second example is explicitly assigned null (which is actually of type null, but due to a quirk of the JavaScript specification, claims to have type object). It is commonly used to clear a value already stored in an existing variable. It could be seen as more robust to use null when clearing the value since it is possible to overwrite undefined, and in that situation assiging undefined would result in unexpected behaviour.



As an aside, that quirk of null is a good reason to use a more robust form of type checking:



Object.prototype.toString.call(null); // Returns [object Null]

[#82279] Sunday, October 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myakylas

Total Points: 66
Total Questions: 85
Total Answers: 95

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
myakylas questions
Thu, Apr 28, 22, 00:00, 2 Years ago
Thu, Apr 8, 21, 00:00, 3 Years ago
Sat, Sep 19, 20, 00:00, 4 Years ago
;