I suppose this is programmer preference but I don't like variables that are undefined. If they are undefined I will assign them some value.
If you have a situation where a variable is either a reference to an object, or it doesn't reference yet:
var my_ref; // undefined
function ref(that_obj) {
my_ref = that_obj;
}
console.log(my_ref); // undefined
ref({"some": "object"});
console.log(my_ref); // {"some": "object"}
My preference is to initialize it to false
. This only works ofcourse if false
is never an expected value. Other values to use are -1
for numbers or null
.
Another example:
function my_func(arg1, arg2, arg3) {
if (has_no_value(arg3)) {
arg3 = "default value";
}
console.log(arg1, arg2, arg3);
}
my_func("first", "lol"); // first lol default value
Also, I recommend making a function that checks for undefined-ness (has_no_value
in my case) because it's easy to make a mistake in typeof arg3 === "undefined"
if(arg3)
is false if arg3 is falsy which includes undefined null 0 "" false NaN
if you want to check for false
do if (false === arg3)
Type coercion is used in JavaScript with the == and != operators. From
Wikipedia: “There are two types of type conversion: implicit and
explicit. The term for implicit type conversion is coercion. The most
common form of explicit type conversion is known as casting.” What
this means is that true and false are converted to numbers before they
are compared to a number. When comparing to any of these values: 0,
null, undefined, '', true and false, Douglas Crockford, in JavaScript:
The Good Parts, recommends the use of the === or !== operators. In
JSLint, there is a “Disallow == and !=” option, which requires the use
of === and !== in all cases.