var p = new Person("xyz");
Some work has been done with p. Now p should point to nothing.
p = undefined;
or
p = null;
Which approach represents best practice for the empty object reference?
var p = new Person("xyz");
Some work has been done with p. Now p should point to nothing.
p = undefined;
or
p = null;
Which approach represents best practice for the empty object reference?
You're really asking whether the variable should be defined as:
undefined
.or
null
.A Quote from the book Professional JS For Web Developers (Wrox) is appropriate here:
You may wonder why the typeof operator returns 'object' for a value that is null. This was actually an error in the original JavaScript implementation that was then copied in ECMAScript. Today, it is rationalized that null is considered a placeholder for an object, even though, technically, it is a primitive value."
Using null
is rational as it's to be considered as a placeholder for an object, but it wouldn't be wrong of you to use undefined
as long as your system is consistent with it.
You can use both according to your requirement. look into this post for what exactly the difference between the two What is the difference between null and undefined in JavaScript?.
Undefined means a variable has been declared but has no value:
var item;
alert(item); //undefined
alert(typeof item); //undefined
Null is an assignment:
var item= null;
alert(item); //null
alert(typeof item); //object
Correct is:
p = null;
undefined
is reserved for when variables are not initialised or for empty promises.