diff --git a/README.md b/README.md index a7c6483..366687e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1853 TILs and counting..._ +_1854 TILs and counting..._ See some of the other learning resources I work on: @@ -619,6 +619,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Easy Date Comparison With DayJS](javascript/easy-date-comparison-with-dayjs.md) - [Expand Emojis With The Spread Operator](javascript/expand-emojis-with-the-spread-operator.md) - [Fill An Input With A Ton Of Text](javascript/fill-an-input-with-a-ton-of-text.md) +- [Filter By Truthy Values With Boolean Function](javascript/filter-by-truthy-values-with-boolean-function.md) - [Find The Version Of An Installed Dependency](javascript/find-the-version-of-an-installed-dependency.md) - [Find Where Yarn Is Installing Binaries](javascript/find-where-yarn-is-installing-binaries.md) - [for...in Iterates Over Object Properties](javascript/for-in-iterates-over-object-properties.md) diff --git a/javascript/filter-by-truthy-values-with-boolean-function.md b/javascript/filter-by-truthy-values-with-boolean-function.md new file mode 100644 index 0000000..a72557c --- /dev/null +++ b/javascript/filter-by-truthy-values-with-boolean-function.md @@ -0,0 +1,42 @@ +# Filter By Truthy Values With Boolean Function + +The `Boolean` function (not to be confused with the `Boolean` constructor) +evaluates any given value to its [boolean +coercion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). + +```javascript +> Boolean(0) +false +> Boolean(1) +true +> Boolean(null) +false +> Boolean([]) +true +``` + +One way that this can be put to use is as a _boolean identity function_ for +passing to other functions like `filter`. + +```javascript +> [0, 1, "", [], "four", null, "six", undefined, 7].filter(Boolean) +[ 1, [], 'four', 'six', 7 ] +``` + +This filters out all the non-truthy values from a list. + +Let's say I'm building a list of nav items that will be rendered to the UI for a +specific user. Based on permissions or feature flags, certain nav items may not +be available. Those "empty" entries can be filtered out in this way. + +```javascript +nav_items = [ + { label: "Home", href: "/" }, + isSystemAdmin && { label: "System", "/system" }, + featureEnabled(user, "api") && { label: "API", "/api" }, +].filter(Boolean) +``` + +If any of those conditional nav items evaluate to `false`, then they will be +filtered out. The resulting `nav_items` array is a clean list of actual nav +items I want to render.