Why you set variable to null at the beginning of JavaScript

I notice that several JavaScript experts begin their code with something like this:


var x = null;

function y() {
	// do something with x
}

What is the benefit of this method. I asked Google and it can’t help me understand the concept.

Thank you,

Hi
I think that the reason is to make sure that the variable is defied, and it is in global scobe (available in all functions).

All variables by default have a null value which is equal to undefined, false, 0 and of course null, to ensure a variable has a true value meaning something meaningful you could simply use the following.

var x;

// Returns "value not defined"
alert('value ' + (x ? 'not' : 'is') + ' defined');

x = 'test';

// Returns "value is defined"
alert('value ' + (x ? 'not' : 'is') + ' defined');

You mean a falsy value. null value is null value, it’s not “equal to undefined, false, 0”, this only adds to the confusion.
EDIT: the default value in JS is undefined.

Again, a falsy value, a true value it’s not.

The discussion here is about three things: undeclared, undefined or null.

Using x without declaring it first (without using an explicit var statement) denotes a variable which declaration will be hoisted by the interpreter. This also usually leads to unexpected behavior, where shadowing a variable leads to a completely different result. The recommendation is to always declare your variables at the top of your scope.

Declaring x outside any function denotes a global variable (usually not a pattern), where, if no value is assigned, a undefined value is the default value. So using var x = null overrides the default undefined value.

Explicitly using var x = null in comparison with undefined, ensures that, when using “===” instead of “==”, you’ll get the right false value, false.


>console.log(null == undefined);
true

> console.log(null === undefined);
false