One-or-the-other properties
We sometimes need a type in which only one of two mutually exclusive properties can be set. Setting either property is fine, setting both isn’t.
Read full articleThese are a collection of tips and tricks you can use to improve the performance and readability of your code.
We sometimes need a type in which only one of two mutually exclusive properties can be set. Setting either property is fine, setting both isn’t.
Read full articleTo asynchronously fetch data in a React component using hooks, we can define and then call an asynchronous function inside of useEffect.
Read full articleJust as we can destructure all other objects, we can destructure functions like log() and warn() directly out of the console object.
Read full articleTo find the largest value in an array of numbers, we can spread that array into Math.max() instead of manually iterating over it.
Read full articleThere is no “array” type in JavaScript. To check if something is an array, we can use a helper on the Array prototype.
Read full articleLookup objects can replace long if-else and switch statements. Checking if a key exists before accessing it makes them more resilient.
Read full articleFinding an object with a specific property is slow in large arrays. We can speed this operation up by transforming the array to a lookup object.
Read full articleWhen a feature calls for the first five photos from a list and a link that says “27 more photos”, we can split the list into these two blocks.
Read full articleInfinity is just a number, dude. Most calculations JavaScript lets us do with Infinity will still return Infinity. Some no longer return numbers.
Read full articleWith JavaScript’s built-in formatter for relative timestamps, we can build strings like “2 months from now” without third party libraries.
Read full articleBy combining regular expressions and parseFloat, we can create a helper function that extracts all float values from a text input.
Read full articleCombining the map function on arrays and type constructors allows us to quickly map values from one type to another.
Read full articleThe ternary operator can be used at many levels. The further we move it into a statement, the more duplication it can save us.
Read full articleUsing .replace() on strings only replaces the first occurrence of a substring by default. We can extend that with a “global” flag on the expression.
Read full articleRegular JavaScript has no concept of required parameters. We can use default parameter values to emulate this feature.
Read full articleIf an expression returns a Boolean value, we don’t also need to compare that result to true or false.
Read full articleWe commonly increment a number using the += operator. Did you know there are assignment shorthands for other operations as well?
Read full articleTo remove the largest value from an array of numbers we first need to find that number and can then filter it out.
Read full articleWe can pass an array to JavaScript’s sort function to sort an array of objects by one of their properties.
Read full articleAs soon as a concatenation of conditions is clear, JavaScript stops the evaluation. It does not do work that does not change the result.
Read full articleInstead of removing elements from an array one by one, we can modify the array itself to clear it in one operation.
Read full articlePutting complex logic into a function increases code readability. By giving that function a descriptive name, it can explain what is happening in it.
Read full articleWe can “freeze” objects to make it impossible to change them after their creation.
Read full articleWe no longer need to install dependencies to pad a string with characters to the left or right of it.
Read full articleWhen your data can contain “outliers” that are clearly unintentional, you can clamp them to all fall within the same valid range.
Read full articleWe can turn arrays of key-value-pairs into objects with a function that is available on Object.
Read full articleAdd thrill and chaos to your code by adding a helper that only sometimes causes an infinite loop.
Read full articleWe can write a function that gives us the array object with the largest value for a specified property.
Read full articleThis helper function lets us remove all instances of specific values from an array.
Read full articlePassing functions to other functions allows us to condense logic into a few lines of code.
Read full articleWe can chain many functions together into a single function. That new function takes one input and runs it through its individual functions one by one.
Read full articleWith this helper function, we can map over objects and change each of their values like we would do with arrays.
Read full articleIf an array contains flat values, we can turn them into objects where they become a property’s value.
Read full articleWant to create annoying memes but are too lazy to hit the shift key every other letter? Don’t worry, I got you.
Read full articleYet another use for the ternary operator: only change the values in an array that match a condition.
Read full articleAccessing deeply nested values required us to check for undefined along the way. With optional chaining, we no longer need to do that.
Read full articleTo quickly access all objects that share the same value for a property, we can group them by that property first.
Read full articleAn “XOR” operation returns the elements that only exist in one of two arrays, but not both.
Read full articleArrays can contain the same value many times, while sets cannot. We can filter an array to unique values by using this difference.
Read full articleUntil we get a native method on the array prototype itself, we can write a helper to get the last element in an array.
Read full articleIf you keep seeing stars in JavaScript, it’s probably someone trying to raise a number to the power of another number.
Read full articleThere are several ways to concatenate in JavaScript. We can pick the one that is most readable in each situation.
Read full articleWe can un-nest arrays with a native function now. We can also define how many levels of nesting we want to take out, to a maximum of “all levels”.
Read full articleWith the Fisher-Yates algorithm, we can shuffle an array with true randomness. The likelihood of two shuffles giving the same result is minimal.
Read full articleWe can create a helper function that makes functions return their Boolean opposite. This can be useful in the shorthand syntax for array methods.
Read full articleInstead of splitting strings at sequences of characters, we can split them into substrings of equal length by using a regular expression.
Read full articleBy destructuring the return value of a function, we can take out only the values we need without having to assign the result to an object first.
Read full articleTo filter all falsy values from arrays, all we need to do is pass the Boolean constructor to the filter function.
Read full article“Zipping” refers to taking the values in two arrays and combining them into a single array of value pairs.
Read full articleWe’re often extracting properties from an array of objects. With a higher-order function, this becomes more readable and easier to do.
Read full articleWe can use the value returned by Math.random() to get a random element from an array.
Read full articleWe can split an array in two based on a condition: matches go in the first array, everything else goes in the second.
Read full articleWe can combine filter and includes to find which elements exist in both of two given arrays.
Read full articleWe can turn arrays of absolute numbers into relative numbers. The largest value becomes 1, with the others calculated based on that largest value.
Read full articleWe can shallowly merge objects without having to type out all properties by hand.
Read full articleWhen you don’t want to drag a full object through your code, you can pick just the properties you need using reduce.
Read full articleSince array methods like filter and map return an array themselves, we can chain them one after the other.
Read full articleWe can build a dictionary of a string’s letters to count how many times each letter appears.
Read full articleThe default behavior of sorting arrays assumes every value is a string. That leads to unexpected behavior when working with numbers.
Read full articleThere is now a more convenient way than reduce or loops to check if all elements in an array match a condition.
Read full articleBy combining map and slice, we can write a helper function to split large arrays into many similarly sized blocks. This is useful for features like pagination.
Read full articleWe can reduce an array of numbers into a single value that represents the sum of its values, without needing a traditional for-loop.
Read full articleThis neat little trick makes values logged to the console much more readable with a minor adjustment to how we log it.
Read full articleWhen creating Tailwind CSS-like utility classes, we can use Sass’ loops to save a lot of repetition.
Read full articleWe can use the ternary operator in places where doing the same thing with if-else-branches would take a lot more code.
Read full articleWe can skip the arrow function when we pass the iterator in filter and map through to a second function.
Read full articleDestructuring lets us extract an object’s property into a variable of the same name in very little code.
Read full articleWe can provide default values for variables in a way that respects “real” values that are still falsy.
Read full articleIf a switch-statement only serves to map a key to a value, we can use an object to do the same in fewer lines of code.
Read full articleAre you calling the same function many times with near-identical parameters? Hide that repetition in a higher-order function for more readability.
Read full articleWhen is June the fifth month of the year? When JavaScript is involved, of course. In JavaScript, January is the zero-th month.
Read full articleThe ternary operator isn’t limited to assigning values based on a condition. It also lets us switch between two near identical function calls.
Read full articleBy wrapping code that can fail in try-catch, we can react to and recover from any errors that happen.
Read full articleWe can’t access object properties using dot notation if the property name is dynamic. In those situations, we can use bracket notation instead.
Read full articleWhen splitting strings, the sequence of characters we split at does not appear in the result. We can get all letters by splitting at the empty string.
Read full articleWhen the if-branch already returns, we can omit the keyword else. The execution will only go beyond the if-branch if it doesn’t apply anyways.
Read full articleInstead of passing a list of parameters to a function, we can pass it an object. That way, we have to explicitly label each parameter we pass to it.
Read full articleIf an arrow function immediately returns a value, we don’t have to write the return keyword. The function will still implicitly return that value.
Read full articleWe can hide the repetition in a function’s parameters in a higher-order function.
Read full articleTemplate literals allow us to put the values of variables, the results of calculations, and even return values of function calls into strings.
Read full articleTo improve the readability of React components, we can import the styled-components they use from another file under a ui-namespace.
Read full articleThis is how libraries like Tailwind CSS can use prefixes like `hover:` and `focus:` to apply styles to pseudo classes.
Read full articleWhen chaining conditions together, putting them into named variables makes code more readable.
Read full articleWhen naming variables that hold Boolean values, using a prefix that indicates as much helps with readability.
Read full articleWe can create a sequence of numbers by spreading the keys of one array into another array. We can then change that range any way we like.
Read full articleWe can skip the return keyword if arrow functions immediately return a value. If that value is an object, we need to also wrap it in parentheses.
Read full articleWe can write a single function that reads the global theme instead of doing the same thing for multiple properties.
Read full articleWhen using styled-components in React, we can use destructuring to make our components more readable.
Read full articleLibraries like Tailwind CSS use special characters in their class names. We can use them in our own classes by escaping them.
Read full articleWe usually want to compare two values using three equal signs in JavaScript. There is one exception where two equal signs are more practical.
Read full article