0

I have the following code:

function lastElement(array) {
  if (array.length > 0)
    return array[array.length - 1];
  else
    return undefined;
}

alert(lastElement([ undefined,1, 2]));

Which returns 2 since it doesn't counts the undefined element & that's perfectly fine.Now if i swap the last element in the array with the undefined:

function lastElement(array) {
  if (array.length > 0)
    return array[array.length - 1];
  else
    return undefined;
}

alert(lastElement([ 1, 2,undefined]));

It returns undefined!! Why is it so? Any help appreciated.

I_Debug_Everything
  • 3,776
  • 4
  • 36
  • 48

4 Answers4

6

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

Because "undefined" is treated as an element of an array !!

Janak
  • 4,986
  • 4
  • 27
  • 45
1

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.

Ken Herbert
  • 5,205
  • 5
  • 28
  • 37
1

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

Prasath K
  • 4,950
  • 7
  • 23
  • 35