2

Which one makes more sense

var myVar = null;

myVar = someLogic(); //someLogic() might return a primitive or an object

if(myVar){
  //other logic
}

OR

var myVar;

myVar = someLogic(); //someLogic() might return a primitive or an object

if(myVar){
  //other logic
}
Tintin
  • 2,853
  • 6
  • 42
  • 74
  • 2
    There's no point in initializing a variable other than to set it to a value you want it to have. – Pointy Aug 24 '16 at 18:41
  • 3
    They are not the same. The second case, myVar is set to undefined, not null. – Joseph Young Aug 24 '16 at 18:42
  • 4
    Why did you think it might be best practice to initialize it to `null`? –  Aug 24 '16 at 18:44
  • It's irrelevant for JS. JS is prepared to work with nulls and undefineds without any problem. For logicals purposes both are "FALSE". – Airton Barbosa Aug 24 '16 at 18:48
  • 2
    The best practice clearly would be `var myVar = someLogic();` – Bergi Aug 24 '16 at 19:27
  • If you assign the variable before you use it, it makes no difference whether you initialized it when you declared it. – Barmar Aug 24 '16 at 19:36
  • @Bergi, that doesn't always work - e.g. I want to set a value in the callback of a promise and not declare it there. This will enable the other callback functions further in the promise chain to see the updated value of this variable. – Tintin Aug 24 '16 at 21:06
  • @torazaburo, I did not think it was a best practice. I "asked" whether it was. – Tintin Aug 24 '16 at 21:07
  • @JosephYoung - the question was not whether they are same. The question was whether one has any advantage/disadvantage over other. – Tintin Aug 24 '16 at 21:08
  • @Tintin: You really [should not do that](http://stackoverflow.com/a/28250700/1048572). There are much better ways to pass values between promise callbacks. – Bergi Aug 24 '16 at 21:09
  • @Bergi , thanks for the link! Great answers there. – Tintin Aug 24 '16 at 21:13

1 Answers1

7

In JavaScript, there is generally no good reason to initialize variables to null.

In languages like C, variables should always be initialized before use because there is no guarantee as to the value of an uninitialized variable – it could be 0, 1, 2, or 283942, or anything. However, JavaScript has no such problem. In JavaScript, variables that have been declared but not initialized will always have the value undefined.

undefined is it's own type in JavaScript. When cast to a boolean, it becomes false.

undefined == null returns true, but undefined === null returns false.

Semantically, undefined means that a value has not been set, whereas null means that there is no value, but we might expect one. However, there is no hard rule for this, as you can always assign the value undefined to a variable manually – I wouldn't recommend this.

In general, setting uninitialized variables to null would be a waste of time.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Reid Horton
  • 526
  • 2
  • 7