Skip to content

Commit

Permalink
Include null and undefined elements in flat() examples
Browse files Browse the repository at this point in the history
- I wasn't sure if `null`, `undefined`, and "empty" were equivalent in the eyes of the `flat()` method, so I tried it out in the console and learned that they are not.
- I've modified the example for sparse arrays to include these values so that others don't have to run their own experiments to learn this information. 
- I also included a link to the sparse array documentation. If the way `flat()` handles `null` and `undefined` confuses the reader, I think they are likely to click on this link to educate themselves.
  • Loading branch information
DanKaplanSES authored Sep 29, 2024
1 parent bc3edf4 commit 2089d21
Showing 1 changed file with 4 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ arr4.flat(Infinity);

### Using flat() on sparse arrays

The `flat()` method removes empty slots in arrays:
The `flat()` method removes [empty slots](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) in arrays:

```js
const arr5 = [1, 2, , 4, 5];
Expand All @@ -70,9 +70,9 @@ console.log(arr5.flat()); // [1, 2, 4, 5]
const array = [1, , 3, ["a", , "c"]];
console.log(array.flat()); // [ 1, 3, "a", "c" ]

const array2 = [1, , 3, ["a", , ["d", , "e"]]];
console.log(array2.flat()); // [ 1, 3, "a", ["d", empty, "e"] ]
console.log(array2.flat(2)); // [ 1, 3, "a", "d", "e"]
const array2 = [1, , 3, undefined, ["a", , ["d", , "e"]], null];
console.log(array2.flat()); // [ 1, 3, undefined, "a", ["d", empty, "e"], null ]
console.log(array2.flat(2)); // [ 1, 3, undefined, "a", "d", "e", null ]
```

### Calling flat() on non-array objects
Expand Down

0 comments on commit 2089d21

Please sign in to comment.