There are a couple things you are missing here. :
1) All variable declarations are hoisted to the top of your function by the JS interpeter so ALL variables are undefined until assigned anyway, even the ones that are declared and assigned in the same statement later in the function. This is called "variable hoisting" and is a feature of the Javascript language. So, there is no functional difference between a variable that is defined at the top of the function and one that is defined later in the function. The only thing that affects the possible behavior of the function is where the variable is assigned a value.
So, because of variable "hoisting", a function like this with two inline variable declarations:
function(array) {
for (var i = 0; i < array.length; i++) {
var el = array[i];
if (el > 3) {
array[i] = el * el;
}
}
}
is actually treated like this by the js interpreter (where all variable declarations are hoisted to the beginning of the function):
function(array) {
var i, el;
for (i = 0; i < array.length; i++) {
el = array[i];
if (el > 3) {
array[i] = el * el;
}
}
}
2) A variable that is undefined
has a value. That value is undefined
and can be useful. For example, it is falsey so that it can be tested in an if
statement or any boolean test or it can even be tested explicitly to see if it's undefined
. Here's an example:
function processIfNegative(array) {
var foundNegative;
array.foreach(function(el) {
if (el < 0) {
foundNegative = true;
}
});
if (foundNegative) {
// do some processing
}
}
Now, for readability purposes, I would probably initialize foundNegative to false
myself, but that isn't required because undefined
is already falsey
.
Or, here's an example where you explicitly check for the undefined
value.
function processLowestPositive(array) {
var lowestValue;
array.foreach(function(el) {
if (el >= 0) {
if (lowestValue === undefined) {
lowestValue = el;
} else if (el < lowestValue) {
lowestValue = el;
}
}
});
// if there was a positive value found
if (lowestValue !== undefined) {
// process the lowest positive value
}
}
Note: when testing for the undefined
value explicitly, I always use ===
or !==
so there are no type conversions and I'm sure the value is actually undefined
.