Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array.prototype.filter unexpected output

Background

Recently I was in a job interview, and someone made me a test:

var array = [1, 2, 3];
array[10] = 10;

alert(array.filter( n => n === undefined));

I was confident this was going to alert an array with 7x undefined, or something among those lines.

However, it outputs an empty array, as in an array of length 0.

Question

For me this is perplexing. Can someone help me explain why this is happening ?

like image 503
Flame_Phoenix Avatar asked Mar 02 '17 20:03

Flame_Phoenix


1 Answers

Deleted or uninitialized (on sparse arrays) items are not visited.

Array#forEach

Description

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).

var array = [1, 2, 3, , , , , , , , 10];

console.log(array.filter((n, i) => (console.log(i), n === undefined)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 109
Nina Scholz Avatar answered Sep 28 '22 00:09

Nina Scholz