Array.length Returns Undefined If The Last Element Is Undefined In Javascript
Solution 1:
Because the last element in the array is undefined.
The array has 3 elements 1, 2 and undefined where undefined has the index 2 and the array has a length of 3.
Thus when array[array.length - 1] is returned it is undefined
Solution 2:
Because "undefined" is treated as an element of an array !!
Solution 3:
You are asking it for the last element - the last element is undefined - therefore you are getting back exactly what you asked for.
In the first case it is not ignoring the undefined array element, it is counting it but you are not outputting its value. If you had an array where every value was undefined, every index would return undefined through that function.
Solution 4:
It doesn't says array.length is undefined .. As you are returning last element of the array , it says undefined
function lastElement(array) {
if (array.length > 0)
return array[array.length - 1];
else
return undefined;
}
alert(lastElement([ 1, 2,undefined]));
Here array.length = 3 and array[array.length - 1] = undefined
Post a Comment for "Array.length Returns Undefined If The Last Element Is Undefined In Javascript"