1

What's the difference between

var myvar;

and

var myvar = null;

?

I've just seen both next to next in professional code and wondering what this is all about...

Sliq
  • 15,937
  • 27
  • 110
  • 143
  • 2
    Simply put: `var myvar;` just declared a variable, but the variable is still `undefined`. On the other hand, `var myvar = null;` sets `myvar` to `null`. – voithos Feb 14 '13 at 17:15
  • 2
    [`undefined`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined) and [`null`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/null) are different things. – VisioN Feb 14 '13 at 17:18

3 Answers3

5

One creates myvar (in the current scope) and assigns no value to it (leaving it === undefined).

The other assigns null to it too.

The assignment of null may be significant depending on how other code interacts with the variable. OTOH, it may done for lack of understanding of what it means.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

If you try var myvar; you've defined myvar as undefined that means it simply has not been assigned a value.

but when you try var myvar = null; you've assigned the null literal to the myvar,which means that the variable represents the null, empty, or non-existent reference.

Ramin Omrani
  • 3,673
  • 8
  • 34
  • 60
  • 1
    Note that unless you use `===`, you might not notice a difference; `null` and `undefined` compare loosely equal. But there will be some code that does care. – cHao Feb 14 '13 at 17:27
  • @cHao, yes that's true for comparison.extra rep for nice tip. – Ramin Omrani Feb 14 '13 at 17:32
0

I prefer to use var myvar = null;

Why?

If I'm checking to see if that value is set in the future, null means that it has not been set, where as undefined means that there was probably an error while trying to set myvar somewhere in the code.

Heres some other opinions as well - What reason is there to use null instead of undefined in JavaScript?

Community
  • 1
  • 1
andyzinsser
  • 2,463
  • 2
  • 18
  • 18
  • `undefined` means a value hasn't been set; it basically means "i don't know", and that's what you get if you don't specify a value. `null` means the value was set, but was explicitly set to nothing. As for not knowing whether your values were assigned...if you have that much of a problem knowing whether some error prevented setting a value, perhaps you're catching too many exceptions. :P I've never had such a problem. – cHao Feb 14 '13 at 19:04