Created
March 10, 2021 16:39
-
-
Save kyleshevlin/52385ed3ee8e282dddac38564938dcfc to your computer and use it in GitHub Desktop.
Array.length gotcha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The gotcha | |
function List({ items }) { | |
return ( | |
items.length && items.map((item) => <Item key={item.id} item={item} />) | |
); | |
} | |
// What will happen when the length of `items` is 0? | |
// It'll render a 0 as text in a Text Node, because JSX has to be able | |
// to render any number. Could you imagine a website that couldn't | |
// display a 0 because it's falsy? | |
// Good way #1 - use a ternary | |
function List({ items }) { | |
return items.length | |
? items.map((item) => <Item key={item.id} item={item} />) | |
: null; | |
} | |
// Good way #2 - compare the length to evaluate to a boolean without coercion | |
function List({ items }) { | |
return ( | |
items.length > 0 && items.map((item) => <Item key={item.id} item={item} />) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment