array.length returns undefined if the last element is undefined in javascript -


i have 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 doesn't counts undefined element & that's fine.now if swap last element in array 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 so? appreciated.

because last element in array undefined.

the array has 3 elements 1, 2 , undefined undefined has index 2 , array has length of 3.

thus when array[array.length - 1] returned undefined


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -