π₯ Massive JavaScript Compilation π₯
30 Tips on writing better JavaScript, TypeScript and React π
Shorten your imports statements.
Looong import statements with a lot of ../../../..
Annoying, right?
With TypeScript you can get rid of them by adding a single line in your tsconfig.json file.
Check it out π€©π
Declarative Promise Wrapper.
Does your code get bloated from writing try-catch over and over?
How about wrapping your promises in a try-catch once, and returning the result and potential error as a tuple instead?
Now you can resolve promises in a nice and simple way π
The array .at method? π€―
Array .at returns the item at that index, allowing for positive and negative integers.
Very handy for grabbing the last item.
The array prototype has a method, "flat", which you can use to flatten an array down to a single dimension.
The method takes an optional depth as an argument, specifying how deep a nested array structure should be flattened (defaulting to 1).
Be careful with loose equality comparison.
The loose equality comparison (== or !=) performs an automatic type conversion if needed.
You often end up with unexpected results.
Converting a list of strings to numbers.
Did you know that you can pass the Number constructor as an argument directly to the array methods?
For example, we can use it to easily convert a list of strings into their numerical values π
Use performance .now to measure execution speed.
The performance API will deliver a much more accurate measurement.
Run promises in parallel.
Speed asynchronous tasks up by running them in parallel.
If the tasks don't rely on the result from the previous one, simply wrap them in Promise.all and run them in parallel.
It's much faster π
You can use Object.entries() to iterate through the properties of an object and access both key and value.
No need to do an object lookup for each iteration.
Let's see how we can create a declarative useInterval hook in React.
This is a great way to create display counters, timeouts or to refresh data and update the UI accordingly, in a fixed interval.
Pass arguments as an object.
The meaning becomes much more clear from the names of the properties.
Also, the order doesnβt matter anymore.
Trust me - your teammates will be happy π
Extending the standard built-ins is considered bad practice.
Create your own utility class instead π
(...And share it on NPM, if it's useful to others).
Did you know that you can use the Broadcast Channel API to do basic communication between browser tabs, windows, and iframes?
It's pretty simple π
Here's an example of how you can create a reusable and composable pipe using JavaScript.
Use console.trace instead of console.log.
It will show you the complete call stack when debugging.
Understanding closures.
A closure gives a function access to an outer function's scope, even if the inner function is invoked from a completely different context.
The nullish coalescing operator will return its right-hand operand when the left side is null or undefined. Not just falsy.
When working with numbers, this is typically very useful.
Did you know that you can cancel a fetch request using an AbortController?
A common use-case is React:
If a component unmounts while a fetch call is awaited, it can be useful to abort the call.
Instead of using find(), or manually searching a list for an occurrence, use the array method some() instead.
Itβs built for exactly that purpose.
TypeScript comes with a utility type, 'ReadonlyArray<T>'.
It's equivalent to 'Array<T>', but with all mutating methods removed.
In this way, you can make sure you donβt change your arrays after creation.
Did you know that you can use object destructuring on arrays?
This is very convenient when we need a group of values from specific indexes.
Did you know that you can trigger a "scroll into view" on a specific element using a single function call in JavaScript?
You can even add a "smooth" behavior to get a nice smooth scroll animation.
Try it for yourself π
By using function composition, you can compose functions for different purposes.
In this case, we're using one function to create different "setter" functions for updating state in React.
Use proper variable names - also in callbacks!
Short, concise code is not necessarily an ideal.
Clarity and readability is.
Paying with an extra line is perfectly ok.
Did you know that you can use curly braces with switch-statements?
Takeaways:
πΈ More readable
πΈ Establishes their own block scope
Did you know that you can create your own custom HTML Elements using JavaScript - and then use them in your HTML file just like any other element? π
You can create some pretty powerful experiences using this technique.
Did you know - if you add the option -y to npm init, NPM will create a starter setup for you without having to go through all the questions π
You can set timers using console.time.
This can be useful when debugging slow loops or function calls.
3 options you can pass to addEventListener.
{ once: true } can be a lifesaver on some occasions!
Avoid callback hell while using NodeJS builtins.
You don't need promisify either - from NodeJS 10 and up, you can import the promisified versions directly from '[module]/promises' πͺ
If you got something out of this thread, you will definitely benefit from my e-book, JavaScript In The Industry.
35% off.
Pick it up today π
simonhoiberg.com/ebooks/javascrβ¦
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.