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
}
11
  • 2
    There's no point in initializing a variable other than to set it to a value you want it to have. Commented Aug 24, 2016 at 18:41
  • 3
    They are not the same. The second case, myVar is set to undefined, not null. Commented Aug 24, 2016 at 18:42
  • 4
    Why did you think it might be best practice to initialize it to null? Commented Aug 24, 2016 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". Commented Aug 24, 2016 at 18:48
  • 2
    The best practice clearly would be var myVar = someLogic(); Commented Aug 24, 2016 at 19:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.