Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created March 10, 2021 16:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyleshevlin/52385ed3ee8e282dddac38564938dcfc to your computer and use it in GitHub Desktop.
Save kyleshevlin/52385ed3ee8e282dddac38564938dcfc to your computer and use it in GitHub Desktop.
Array.length gotcha
// 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