2
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?

slevy1
  • 3,797
  • 2
  • 27
  • 33
Md. Arafat Al Mahmud
  • 3,124
  • 5
  • 35
  • 66
  • I'm afraid there's no definite answer on that. Personally I find cleaner to use `null` but that's a matter of taste mainly as both behave mostly the same. – Denys Séguret Dec 15 '14 at 09:50
  • The style shouldn't matter, the garbage collector will handle that for you, what you do have to look out for though is not defining global variables. global variables will not be picked up by the garbage collector. – Bas Tuijnman Dec 15 '14 at 09:57
  • Unless you have code that's using strict comparison with `null` or `undefined`, it doesn't matter. – Barmar Dec 15 '14 at 09:59

3 Answers3

2

It's a matter of of interpretation, but null is rationally a better option

You're really asking whether the variable should be defined as:

  • a variable that has been declared but has not yet been assigned a value, i.e. undefined.

or

  • an assignment value as a representation of no value, i.e. 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."

Conclusion:

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.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • People who answer basically as *"do as you want, I prefer this way"*, you should close as *"Primarily Opinion based"* instead. – Denys Séguret Dec 15 '14 at 10:03
  • @dystroy You're right, but I believe my edited answer is somewhat further away from an simple opinion. – Jonast92 Dec 15 '14 at 10:09
0

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
Community
  • 1
  • 1
sitaram9292
  • 171
  • 8
-2

Correct is:

p = null;

undefined is reserved for when variables are not initialised or for empty promises.

Loopo
  • 2,204
  • 2
  • 28
  • 45
Oyola
  • 1
  • 1