Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

Top 10 new JavaScript features from 2021 to 2023

These 10 amazing features were all about writing shorter, safer, and more expressive code.

1. Private methods and fields

We need our privacy. There’s no two ways about it.

And so do OOP classes; but in JavaScript it was once impossible to strictly declare private members.

It was once impossible to declare private members in a JavaScript class.

A member was traditionally prefixed with an underscore (_) to indicate that it was meant to be private, but it could still be accessed and modified from outside the class.

JavaScript
class Person { _firstName = 'Coding'; _lastName = 'Beauty'; get name() { return `${this._firstName} ${this._lastName}`; } } const person = new Person(); console.log(person.name); // Coding Beauty // Members intended to be private can still be accessed // from outside the class console.log(person._firstName); // Coding console.log(person._lastName); // Beauty // They can also be modified person._firstName = 'Debugging'; person._lastName = 'Nightmares'; console.log(person.name); // Debugging Nightmares

With ES2022, we can now add private fields and members to a class, by prefixing it with a hashtag (#). Trying to access them from outside the class will cause an error:

JavaScript
class Person { #firstName = 'Coding'; #lastName = 'Beauty'; get name() { return `${this.#firstName} ${this.#lastName}`; } } const person = new Person(); console.log(person.name); // SyntaxError: Private field '#firstName' must be // declared in an enclosing class console.log(person.#firstName); console.log(person.#lastName);

Note that the error thrown here is a syntax error, which happens at compile time; the code doesn’t run at all; the compiler doesn’t expect you to even try to access private fields from outside a class, so it assumes you’re trying to declare one.

“Ergonomic brand” checks for private fields

With private fields come a new keyword to safely check if a class object contains a particular one — the in keyword:

JavaScript
class Car { #color; hasColor() { return #color in this; } } const car = new Car(); console.log(car.hasColor()); // true;

It correctly distinguishes private fields with the same names from different classes:

JavaScript
class Car { #color; hasColor() { return #color in this; } } class House { #color; hasColor() { return #color in this; } } const car = new Car(); const house = new House(); console.log(car.hasColor()); // true; console.log(car.hasColor.call(house)); // false console.log(house.hasColor()); // true console.log(house.hasColor.call(car)); // false

And don’t ask me about the name; I also have no idea why they’re called that (do you?).

Ergonomics as far as I’m concerned is all about keeping good sitting posture while using your computer (?) 🤔.

Although I guess you could twist this definition to allow for this new feature — or any new feature for that matter. They’re all about comfort, right? Less pain writing code.

But I guess English isn’t a closed language and you can always add new words and additional definitions (just ask Shakespeare).

2. Immutable sort(), splice(), and reverse()

ES2023 came fully packed with immutable versions of these 3 heavily used array methods.

Okay maybe splice() isn’t used as much as the others, but they all mutate the array in place.

JavaScript
const original = [5, 1, 3, 4, 2]; const reversed = original.reverse(); console.log(reversed); // [2, 4, 3, 1, 5] (same array) console.log(original); // [2, 4, 3, 1, 5] (mutated) const sorted = original.sort(); console.log(sorted); // [1, 2, 3, 4, 5] (same array) console.log(original); // [1, 2, 3, 4, 5] (mutated) const deleted = original.splice(1, 2, 7, 10); console.log(deleted); // [2, 3] (deleted elements) console.log(original); // [1, 7, 10, 4, 5] (mutated)

Immutability gives us predictable and safer code; debugging is much easier as we’re certain variables never change their value.

Arguments are exactly the same, with splice() and toSpliced() having to differ in their return value.

JavaScript
const original = [5, 1, 3, 4, 2]; const reversed = original.toReversed(); console.log(reversed); // [2, 4, 3, 1, 5] (copy) console.log(original); // [5, 1, 3, 4, 2] (unchanged) const sorted = original.toSorted(); console.log(sorted); // [1, 2, 3, 4, 5] (copy) console.log(original); // [5, 1, 3, 4, 2] (unchanged) const spliced = original.toSpliced(1, 2, 7, 10); console.log(spliced); // [1, 7, 10, 4, 5] (copy) console.log(original); // [5, 1, 3, 4, 2] (unchanged)

3. Top-level await

Did you know: F# was the first language to introduce async/await? As far back as 2007! But it took JavaScript 10 good years to catch up.

await pauses execution in the async context until a Promise resolves.

Previously we could only use this operator in an async function, but it could never work in the global scope.

JavaScript
function setTimeoutAsync(timeout) { return new Promise((resolve) => { setTimeout(() => { resolve(); }, timeout); }); } // SyntaxError: await is only valid in async functions await setTimeoutAsync(3000);

With ES2022, now we can:

JavaScript
function setTimeoutAsync(timeout) { return new Promise((resolve) => { setTimeout(() => { resolve(); }, timeout); }); } // ✅ Waits for timeout - no error thrown await setTimeoutAsync(3000);

4. Promise.any()

If you know Promise.all(), then you can easily guess what this does: wait for one Promise to resolve and return the result.

JavaScript
async function getHelpQuickly() { const response = await Promise.any([ cautiousHelper(), kindHelper(), wickedHelper(), ]); console.log(response); // Of course! } async function cautiousHelper() { await new Promise((resolve) => { setTimeout(() => { resolve('Uum, oohkaay?'); }, 2000); }); } async function kindHelper() { return 'Of course!'; } function wickedHelper() { return Promise.reject('Never, ha ha ha!!!'); }

Point to note: Promise.any() still waits for *all* the promises in the current async context to resolve, even though it only returns the result of the first one.

JavaScript
await getHelpQuickly(); // outputs "Of course!" immediately // Still waits for 2 seconds

5. Array find from last

Array find() searches for an array element that passes a specified test condition, and findIndex() gets the index of such an element.

While find() and findIndex() both start searching from the first element of the array, there are instances where it would be preferable to start the search from the last element instead.

There are scenarios where we know that finding from the last element might achieve better performance. For example, here we’re trying to get the item in the array with the value prop equal to y. With find() and findIndex():

JavaScript
const letters = [ { value: 'v' }, { value: 'w' }, { value: 'x' }, { value: 'y' }, { value: 'z' }, ]; const found = letters.find((item) => item.value === 'y'); const foundIndex = letters.findIndex((item) => item.value === 'y'); console.log(found); // { value: 'y' } console.log(foundIndex); // 3

This works, but as the target object is closer to the tail of the array, we might be able to make this program run faster if we use the new ES2022 findLast() and findLastIndex() methods to search the array from the end.

JavaScript
const letters = [ { value: 'v' }, { value: 'w' }, { value: 'x' }, { value: 'y' }, { value: 'z' }, ]; const found = letters.findLast((item) => item.value === 'y'); const foundIndex = letters.findLastIndex((item) => item.value === 'y'); console.log(found); // { value: 'y' } console.log(foundIndex); // 3

Another use case might require that we specifically search the array from the end to get the correct item.

If we’re finding the last even number in a list of numbers, find() and findIndex() produces a totally wrong result:

JavaScript
const nums = [7, 14, 3, 8, 10, 9]; // gives 14, instead of 10 const lastEven = nums.find((value) => value % 2 === 0); // gives 1, instead of 4 const lastEvenIndex = nums.findIndex((value) => value % 2 === 0); console.log(lastEven); // 14 console.log(lastEvenIndex); // 1

We could call the reverse() method on the array to reverse the order of the elements before calling find() and findIndex(). But this approach would cause unnecessary mutation of the array; reverse() reverses the elements of an array in place.

The only way to avoid this mutation would be to make a new copy of the entire array, which could cause performance problems for large arrays.

Also findIndex() still wouldn’t on the reversed array, as reversing the elements would also mean changing the indexes they had in the original array. To get the original index, we would need to perform an additional calculation, which means writing more code.

JavaScript
const nums = [7, 14, 3, 8, 10, 9]; // Copying the entire array with the spread syntax before // calling reverse() const reversed = [...nums].reverse(); // correctly gives 10 const lastEven = reversed.find((value) => value % 2 === 0); // gives 1, instead of 4 const reversedIndex = reversed.findIndex((value) => value % 2 === 0); // Need to re-calculate to get original index const lastEvenIndex = reversed.length - 1 - reversedIndex; console.log(lastEven); // 10 console.log(reversedIndex); // 1 console.log(lastEvenIndex); // 4

It’s cases like where the findLast() and findLastIndex() methods come in handy.

JavaScript
const nums = [7, 14, 3, 8, 10, 9]; const lastEven = nums.findLast((num) => num % 2 === 0); const lastEvenIndex = nums.findLastIndex((num) => num % 2 === 0); console.log(lastEven); // 10 console.log(lastEvenIndex); // 4

This code is shorter and more readable. Most importantly, it produces the correct result.

6. String replaceAll()

We already had replace() for quickly replace a substring within a string.

JavaScript
const str = 'JavaScript is so terrible, it is unbelievably terrible!!'; const result = str.replace('terrible', 'wonderful'); console.log(result); // JavaScript is so wonderful, it is unbelievably terrible!! // Huh?

But it only does so for the first occurrence of the substring unless you use a regex; now we have replaceAll() to replace every single instance of that substring.

JavaScript
const str = 'JavaScript is so terrible, it is unbelievably terrible.'; const result = str.replaceAll('terrible', 'wonderful'); console.log(result); // JavaScript is wonderful, it is unbelievably wonderful. // Now you're making sense!

7. Array with() and at()

at() came first and with() came a year after that in 2023.

They are the functional and immutable versions of single-element array modification and access.

JavaScript
const colors = ['pink', 'purple', 'red', 'yellow']; console.log(colors.at(1)); // purple console.log(colors.with(1, 'blue')); // ['pink', 'blue', 'red', 'yellow'] // Original not modified console.log(colors); // ['pink', 'purple', 'red', 'yellow']

The cool thing about these new methods is how they let you get and change element values with negative indexing.

JavaScript
// index -N is same as index arr.length - N const fruits = ['banana', 'apple', 'orange', 'butter???']; console.log(fruits.at(-3)); // apple console.log(fruits.at(-1)); // butter??? console.log(fruits.with(-1, 'watermelon')); // ['banana', 'apple', 'orange', 'watermelon'] ✅

8. static static static

Static class fields, static private methods (2022).

Static methods access other private/public static members in the class using the this keyword; instance methods with this.constructor:

JavaScript
class Person { static #count = 0; static getCount() { return this.#count; } // Instance method constructor() { this.constructor.#incrementCount(); } static #incrementCount() { this.#count++; } } const person1 = new Person(); const person2 = new Person(); console.log(Person.getCount()); // 2

Static blocks.

Executed only once when the *class* is created. It’s like static constructors in other OOP languages like C# and Java.

JavaScript
class Vehicle { static defaultColor = 'blue'; } class Car extends Vehicle { static colors = []; static { this.colors.push(super.defaultColor, 'red'); } static { this.colors.push('green'); } } console.log(Car.colors); // [ 'blue', 'red', 'green' ]

When they’re multiple static blocks, they’re executed in the order they’re declared, along with any static fields in between. The super property in a static block to access properties of the superclass.

9. Logical assignment operators

They let a variable perform a logical operation with another variable and re-assign the result to itself.

We use them like this:

JavaScript
left ??= right; left ||= right; left &&= right;

They’re as good as:

JavaScript
// More like exactly the same as left = (left ?? right); left = (left || right); left = (left && right);

??=. Quickly assign a value to a variable *if* it is null or undefined (“nullish”).

JavaScript
user.preferredName ??= generateDumbUserName();

||=. Like ??=, but assigns the value for any falsy value (0, undefined, null, '', NaN, or false).

JavaScript
user.profilePicture ||= "/angry-stranger.png";

And then &&=. Something like the reverse; only assigns when the value is truthy (not falsy).

JavaScript
user.favoriteLanguage = await setFavoriteLanguage(input.value); user.favoriteLanguage &&= 'Assembly'; // You're lying! It's Assembly!

10. Numerical separators

Tiny new addition to make big number literals more readable and human-friendly.

JavaScript
const isItPi = 3.1_415_926_535; const isItAvagadro = 602_214_076_000_000_000_000_000; const isItPlanck = 6.626_070_15e-34; const isItG = 6.674_30e-11; // Works for other number bases too...

The compiler completely ignores those pesky underscores — they’re all for you, the human!

Final thoughts

These are the juicy new JavaScript features that arrived in the last 3 years. Use them to boost your productivity as a developer and write cleaner code with greater conciseness, expressiveness and clarity.

New JavaScript pipeline operator: transform anything into a one-liner

With the pipeline operator you’ll stop writing code like this:

and start writing code like this:

So refreshingly clean — and elegant! All those temporary variables are gone — not to mention the time it took to come up with those names *and* type them (not everyone types like The Flash, unfortunately).

The Flash
A fast typist, apparently.

You may have heard this partially true quote attributed to Phil Karlton: “There are only two hard things in computer science: cache invalidation and naming things“.

Using the JavaScript pipeline operator clears out the clutter to boost readability and write data transforming code (basically all code) in a more intuitive manner.

Verbosity should be avoided as much as possible, and this works so much better to compact code than reusing short-named variables:

Hopefully, almost no one codes like this on a regular basis. It’s a pretty horrible technique when done in a large scale; a perfect example showing why we embrace immutability and type systems.

Unlike the pipeline operator, there’s no certainty that the variable always contains the value you set at any given point; you’ll need to climb up the scope to look for re-assignments. We can have used the _ at an earlier point in the code; the value it has at various points in the code is simply not guaranteed.

Now we’re just using an underscore, so without checking out the right-hand side of those re-assignments you can’t quickly know what the type of the variable is, unless you have a smart editor like VS Code (although I guess you could say that doesn’t matter since they’re supposed to be “temporary” — at least until they’re not!).

All in all, poor readability. Fragile and Unstable. 5 times harder for someone new to understand. Also, some would say underscores are “ugly”, especially in languages like JavaScript where they hardly show up.

Okay, so why don’t we just avoid this infestation of temporary underscores, and nest them into one gigantic one-liner?

It’s a mess. The underscore is gone, but who in the world can understand this at a glance? How easy is it to tell how the data flows throughout this code, and make any necessary adjustments.

Understanding, at a glance — this is what we should strive for with every line of code we write.

The pipeline operator greatly outshines every other method, giving us both freedom from temporary variables and readability. It was designed for this.

Here the % only exists within this particular pipeline.

Method chaining?

Who hasn’t used and combined heavily popular array methods like map, filter, and sort? Very hard to avoid in applications involving any form of list manipulation.

This is actually great. There aren’t any temporary variables or unreadable nesting here either and we can easily follow the chain from start to finish.

The formatting lets us easily add more methods at any point in the chain; feature-packed editor like VS Code can easily swap the processing order of two methods, with the Ctrl + Up and Ctrl + Down shortcuts.

There’s a reason why libraries like core http and jQuery are designed like this:

The problem with method chaining is that, we simply can’t use it everywhere. If the class wasn’t designed like that we’re stuck and out in the cold.

It doesn’t work very well with generator methods, async/await and function/method calls outside the object, like we saw here:

But all this and more work with the pipeline operator; even object literals and async import function.

Could have been F# pipes

We would have been using the pipeline operator very similarly to F# pipes, with the above turning out like this instead:

There was an alternative design. But you can already see how this makes for an inferior alternative: Only single-function arguments are allowed and the operation is more verbose. Unless the operation is already a single-argument function call.

It’s weird handling of async/await was also a key reason why it got rejected — along with memory usage concerns. So, forget about F# pipes in JS!

Use the pipeline operator right now

Yes you can — with Babel.

Babel has a nice habit of implementing features before they’re officially integrated in the language; it did this for top-level await, optional chaining, and many others. The pipeline operator couldn’t be an exception.

Just use the @babel/plugin-proposal-pipeline-operator plugin and you’re good to.

It’s optional of course — but not for long.

Prettier the code formatter is already prepared.

Even though we can’t say the same about VS Code or Node.js.

Right now there’s even speculation that % won’t be the final symbol pass around in the pipeline; let’s watch and see how it all plays out.

Final thoughts

It’s always great to see new and exciting features come to the language. With the JavaScript pipeline operator, you’ll cleanse your code of temporary variables and cryptic nesting, greatly boost code readability, efficiency, and quality.

Fix “Cannot read property ‘map’ of undefined” in React

Are you currently experiencing the “Cannot read property ‘map’ of undefined” error in your React app?

The "Cannot read properties of undefined (reading 'map')" error in the browser console.
The “Cannot read properties of undefined (reading ‘map’)” error in the browser console.

This error happens when you call the map() method on a variable that was meant to be an array, but is actually undefined. The variable could be a property or state variable.

For example:

JavaScript
import { useState, useEffect } from 'react'; import { fetchBooks } from './books'; function App() { // ❌ `books` is `undefined` const [books, setBooks] = useState(undefined); useEffect(() => { (async () => { setBooks(await fetchBooks()); })(); }, []); return ( <div> {books.map((book) => ( <div key={book.id}> <h2>Title: {book.title}</h2> <p>Author: {book.author}</p> </div> ))} </div> ); } export default App;

We’ll use this example to learn some easy ways to quickly fix this error in React.

Fix: Use optional chaining operator (?.)

To fix the “Cannot use property ‘map’ of undefined” error in React.js, use the optional chaining operator (?.) to access the map() method:

JavaScript
import { useState, useEffect } from 'react'; import { fetchBooks } from './books'; function App() { const [books, setBooks] = useState(undefined); useEffect(() => { (async () => { setBooks(await fetchBooks()); })(); }, []); return ( <div> {/* ✅ Fix with optional chaining (?.) */} {books?.map((book) => ( <div key={book.id}> <h2>Title: {book.title}</h2> <p>Author: {book.author}</p> </div> ))} </div> ); } export default App;

The optional chaining operator lets us safely access a property on a value that may be undefined or null. If it is, the operator will return undefined immediately and prevent the property access or method call.

JavaScript
const auth = undefined; console.log(auth); // undefined // ✅ No error console.log(auth?.user?.name); // undefined

Fix: Use AND operator (&&)

You can also use the && operator to check if the value is undefined before access it in the JSX:

JavaScript
import { useState, useEffect } from 'react'; import { fetchBooks } from './books'; function App() { const [books, setBooks] = useState(undefined); useEffect(() => { (async () => { setBooks(await fetchBooks()); })(); }, []); return ( <div> {/* ✅ Fix with AND operator (&&) */} {books && books.map((book) => ( <div key={book.id}> <h2>Title: {book.title}</h2> <p>Author: {book.author}</p> </div> ))} </div> ); } export default App;

Here’s what a chain of && does: it returns the right-most variable if all the variables are truthy. Otherwise, it returns the left-most falsy variable:

JavaScript
console.log(undefined && 0 && []); // undefined console.log(10 && null && 'coding'); // null console.log(10 && [5, 7] && 'coding'); // coding

Note: These are the falsy values in JavaScript: undefined, null, 0, false, '' (empty string), and NaN. Every other value is truthy.

Fix: Initialize state variable to empty array

The applies when the array value is a state variable like in our example.

We set the state to an empty array ([]) at the point where it’s created, so it never becomes undefined, preventing the “Cannot read property ‘map’ of undefined” error.

JavaScript
import { useState, useEffect } from 'react'; import { fetchBooks } from './books'; function App() { // ✅ `books` starts out as an array, not `undefined` const [books, setBooks] = useState([]); useEffect(() => { (async () => { setBooks(await fetchBooks()); })(); }, []); return ( <div> {books.map((book) => ( <div key={book.id}> <h2>Title: {book.title}</h2> <p>Author: {book.author}</p> </div> ))} </div> ); } export default App;

Fix: Create a loading state when fetching data

Apart from initializing the state to an empty array you can also display a loading indicator when performing network request, or some other time-consuming operation:

JavaScript
import { useState, useEffect } from 'react'; import { fetchBooks } from './books'; function App() { const [books, setBooks] = useState(undefined); const [loading, setLoading] = useState(true); useEffect(() => { (async () => { setBooks(await fetchBooks()); })(); // ✅ Lists books with .map() after loading completes setLoading(false); }, []); let listEl; if (loading) { listEl = <div>Loading...</div>; } else { listEl = ( <div> {books.map((book) => ( <div key={book.id}> <h2>Title: {book.title}</h2> <p>Author: {book.author}</p> </div> ))} </div> ); } return <div>{listEl}</div> } export default App;

Most web user interfaces have at least three states – loading, error, and success state, and we could be better off representing all three of them:

JavaScript
import { useState, useEffect } from 'react'; import { fetchBooks } from './books'; // TypeScript // type UIState = 'loading' | 'error' | 'success'; function App() { const [books, setBooks] = useState(undefined); const [state, setState] = useState('loading'); // TypeScript // const [state, setState] = useState<UIState>('loading'); useEffect(() => { try { (async () => { setBooks(await fetchBooks()); setState('success'); })(); // ✅ Lists books with .map() after loading completes } catch (err) { setState('error'); } }, []); const listViewMap = { loading: <div>Loading...</div>, error: <div>An error occured, try again later.</div>, success: ( <div> {books.map((book) => ( <div key={book.id}> <h2>Title: {book.title}</h2> <p>Author: {book.author}</p> </div> ))} </div> ), }; const listEl = listViewMap[state]; return <div>{listEl}</div>; } export default App;

Fix: Check the value assigned to the array

Maybe you initialized the array properly and did everything else right, but you set it to undefined at some point in the code.

If the array is to be filled with API data, are you sure you’re making the network request properly.

For example, if our fetchBooks() function was defined like below, it will cause a “Cannot read property ‘map’ of undefined” error when there’s a network error on the user’s device.

JavaScript
export async function fetchBooks() { const res = fetch('https://api.example/books', { headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }); // ❌ Will return `undefined` if status code is not 200 return res.status === 200 ? (await res).json() : undefined; }

Make sure you handle all the edge cases in your app.

Fix: Check your variable names

Sometimes the error happens due to a error in your variable names.

JavaScript
import { useState, useEffect } from 'react'; import { fetchBooks } from './books'; function App() { const [books, setBooks] = useState([]); useEffect(() => { (async () => { setBooks(await fetchBooks()); })(); }, []); return ( <div> {books.map((books) => ( <div key={book.id}> <h2>Title: {book.title}</h2> <p>Author: {book.author}</p> </div> ))} </div> ); } export default App;

Here we mistakenly create a books variable in the map() callback but we use book identifier in the JSX, which is what we actually intended. The causes the unfortunate error, aside from the fact that it shadows the outer books state variable.

Master JavaScript generators: 5 inspiring practical use cases

You will be an expert on JavaScript generators by the time you’re done reading this.

JavaScript generators are way more than just a fancy feature and we are going to discover many powerful use cases for them, including creating engaging animations, and streaming videos over the internet.

If you’ve never heard of them you may be missing out.

Generators are simply functions that you can pause and resume whenever you want — they don’t execute continuously.

The asterisk * marks the function as a generator, and yield generates values on demand from a .next() call, until the generator is done.

JavaScript
function* myGenerator() { yield 'Hello'; yield 'World'; } const iterator = myGenerator(); console.log(iterator.next()); // {value: 'Hello', done: false} console.log(iterator.next()); // {value: 'World', done: false} console.log(iterator.next()); // {value: undefined, done: true}

It’s just like how a physical generator produces electricity not all at once, but as time goes on.

Instead of calling next() you can use the for..of loop, which is great for when the generator generates a lot of data.

JavaScript
function* countTo100() { for (let i = 0; i < 100; i++) { yield i; } } for (const item of countTo100()) { console.log(item); } // 1, 2, ... 100

Lazy evaluation

“Calculate only when necessary.”

Much unlike regular functions in JavaScript that execute entirely and return the result.

Let’s say you want a sequence of numbers, but you’re not sure how many. Here’s how a generator helps:

JavaScript
function* numberGenerator() { let number = 1; // infinite loop won't cause freeze in generator // -- execution pauses after `yield` while (true) { yield number++; } } const numbers = numberGenerator(); console.log(numbers.next().value); // 1 console.log(numbers.next().value); // 2 // you can continue this as long as you need

With generators, you get the next number only when you ask for it.

Better memory utilization

Generators don’t hold all the results in memory, they generate them on the fly.

Imagine you need a sequence of a million numbers. With a regular function, you’d need to store all these numbers in an array, using up significant memory.

A generator is much more efficient:

JavaScript
function* bigNumberGenerator() { let number = 1; while (number <= 100000000) { yield number++; } } const bigNumbers = bigNumberGenerator(); const chunk = 10; for (let i = 0; i < chunk; i++) { const value = bigNumbers.next().value; // Use next 10 values... }

Handling asynchronous tasks

Did you know that Babel transpiles async/await to generators for JavaScript versions that don’t support it natively?

Babel tranforms this:

JavaScript
this.it('is a test', async function () { const name = await 'coding beauty' const num = await new Promise(resolve => resolve(10)); console.log(`Name: ${name}, Num: ${num}`); });

To this:

JavaScript
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then( function (value) { return step('next', value); }, function (err) { return step('throw', err); } ); } } return step('next'); }); }; } myFunc( 'generator async/await example', _asyncToGenerator(function* () { const name = yield 'coding beauty'; // yield, not await const num = yield new Promise((resolve) => resolve(10)); console.log(`Name: ${name}, Num: ${num}`); }) );

Typing animations

Typing animations grab the attention of users and make your website more visually appealing.

They add personality and character to a website by mimicking the typing behavior of a human to create a more human-like experience and establish a unique brand identity.

So with all these benefits you’re feeling excited about infusing your webpages with these energetic visual effects.

Here would be a decent way to go about it, using recursion and setTimeout():

JavaScript
function typeAnimation(text, index = 0) { if (index < text.length) { document.body.innerHTML += text.charAt(index); index++; setTimeout(typeAnimation, 500); } }

But, it’s cases like this where generators shine:

JavaScript
function* typeAnimation(text) { for(let char of text) { yield char; } }

Since we can generate values whenever we want, we can do this in time intervals using setInterval().

JavaScript
const generatorInstance = typeGenerator("Coding Beauty"); function startTypingEffect(elementId, generatorInstance) { let element = document.getElementById(elementId); setInterval(() => { let result = generatorInstance.next(); !result.done && element.innerHTML += result.value; }, 100); } startTypingEffect("type-here", generatorInstance);
JavaScript
<div id="type-here"></div>

Asynchronous handling

Note: This is NOT the same as being the bedrock of async/await, like we saw earlier. We’re talking about async generators here.

JavaScript
function* asyncGenerator() { yield new Promise(resolve => setTimeout(() => resolve('Task 1 completed'), 2000)); yield new Promise(resolve => setTimeout(() => resolve('Task 2 completed'), 3000)); // ... }

And here’s how we can use this generator:

JavaScript
const asyncGen = asyncGenerator(); asyncGen.next().value.then(console.log); asyncGen.next().value.then(console.log);

This is such a powerful tool for streaming data in web app in a structured, readable manner — just look at this function that buffers and streams data for a video-sharing app like YouTube:

JavaScript
async function* streamVideo({ id }) { let endOfVideo = false; const downloadChunk = async (sizeInBytes) => { const response = await fetch( `api.example.com/videos/${id}` ); const { chunk, done } = await response.json(); if (done) endOfVideo = true; return chunk; }; while (!endOfVideo) { const bufferSize = 500 * 1024 * 1024; yield await downloadChunk(bufferSize); } }

To consume this async generator, we’d use the for await..of loop:

JavaScript
for await (const chunk of streamVideo({ id: 2341 })) { // process video chunk }

redux-saga

redux-saga is a library for managing side effects in applications, boasting over 1 million weekly downloads.

Generators play a big role in this library, handling the redux actions to make testing and error handling easier.

Take a look at this simple saga:

JavaScript
import { call, put, takeEvery } from 'redux-saga/effects'; function* fetchData(action) { try { const data = yield call(Api.fetchUser, action.payload.userId); yield put({type: "USER_FETCH_SUCCEEDED", data}); } catch (e) { yield put({type: "USER_FETCH_FAILED", message: e.message}); } } function* mySaga() { yield takeEvery("USER_FETCH_REQUESTED", fetchData); }
JavaScript
import createSagaMiddleware from 'redux-saga'; import { createStore, applyMiddleware } from 'redux'; import mySaga from './sagas'; const sagaMiddleware = createSagaMiddleware(); const store = createStore( reducer, applyMiddleware(sagaMiddleware) ); sagaMiddleware.run(mySaga)

Whenever the USER_FETCH_REQUESTED action is dispatched, redux-saga runs the generator which in turn calls fetchData() to perform the asynchronous network request.

A note on return

What happens when you return a value in a generator function? Let’s see:

JavaScript
function* soccerPlayers() { yield 'Ronaldo'; yield 'Messi'; return 'Neymar'; } for (const player of soccerPlayers()) { console.log(player); } // Ronaldo // Messi

Why isn’t Neymar part of the generated values?

Let’s use .next() to find out if the done property has something to do with it:

JavaScript
function* soccerPlayers() { yield 'Ronaldo'; yield 'Messi'; return 'Neymar'; } const playerGen = soccerPlayers(); console.log(playerGen.next()); console.log(playerGen.next()); console.log(playerGen.next()); /* { value: 'Ronaldo', done: false } { value: 'Messi', done: false } { value: 'Neymar', done: true } */

It turns out that return is not considered a generated value, so for..of doesn’t process it.

Do you remember our very first example:

JavaScript
function* myGenerator() { yield 'Hello'; yield 'World'; } const iterator = myGenerator(); console.log(iterator.next()); // {value: 'Hello', done: false} console.log(iterator.next()); // {value: 'World', done: false} console.log(iterator.next()); // {value: undefined, done: true}

You can see that generators only produce values until, but not including when done is true.

So return completes the generator and terminates the function (like any other).

JavaScript
function* myGenerator() { yield 'Hello'; return 'End'; yield 'This will not be executed'; }

Final thoughts

JavaScript generators offer powerful solutions for control flow, memory efficiency, and asynchronous handling. They enhance web development with dynamic animations, streaming data, and managing side effects.

Let’s embrace the versatility of generators for elegant and efficient JavaScript programming.

[SOLVED] Cannot use import statement outside a module in JavaScript

Are you currently experiencing the “Cannot use import statement outside a module” error in JavaScript?

The "Cannot use import statement outside a module" error in a browser console.
The “Cannot use import statement outside a module” error in a browser console.

This is a well-known error that happens when you use the import keyword to load a file or package that is not a module.

Let’s learn how to easily fix this error in Node.js or the browser.

Fix “Cannot use import statement outside a module” in browser

Fix: Set type="module" in <script> tag

The “Cannot use import statement outside a module” error happens in a browser when you import a file that is a module without indicating this in the <script> tag.

index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty</title> <link rel="icon" href="favicon.ico" /> </head> <body> A site to make you enjoy coding <!-- ❌ SyntaxError: Cannot use import statement outside a module --> <script src="index.js"></script> </body> </html>

To fix it, add type="module" to the <script> tag.

index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty</title> <link rel="icon" href="favicon.ico" /> </head> <body> A site to make you enjoy coding <!-- ✅ Loads script successfully --> <script type="module" src="index.js"></script> </body> </html>

Fix “Cannot use import statement outside a module” in Node.js

The “Cannot use import statement outside a module” error happens when you use the import keyword in a Node.js project that doesn’t use the ES module import format.

index.js
// ❌ SyntaxError: Cannot use import statement outside a module import axios from 'axios'; const { data } = ( await axios.post('https://api.example.com/hi', { hello: 'world', }) ).data; console.log(data);

Fix: Set type: "module" in package.json

To fix the error in Node.js, set the package.json type field to “module”.

package.json
{ // ... "type": "module", // ... }

Now you can use the import statement with no errors:

index.js
// ✅ Imports successfully import axios from 'axios'; const { data } = ( await axios.post('https://api.example.com/hi', { hello: 'world', }) ).data; console.log(data);

If there’s no package.json in your project, you can initialize one with the npm init -y command.

Shell
npm init -y

The -y flags creates the package.json with all the default options – no user prompts for the fields.

Fix: Use require instead of import

Alternatively, you can fix the “Cannot use import statement outside a module” error in JavaScript by using the require() function in place of the import syntax:

index.js
// ✅ Works - require instead of import const axios = require('axios'); const { data } = ( await axios.post('https://api.example.com/hi', { hello: 'world', }) ).data; console.log(data);

But require() only works on the older, Node-specific CommonJS module system, and these days more and more modules are dropping support for CommonJS in favor of ES6+ modules.

For example, if you use require() for modules like got, node-fetch, and chalk, you’ll get the “require of ES modules is not supported error”.

index.js
// ❌ [ERR_REQUIRE_ESM]: require() of ES Module not supported const chalk = require('chalk'; console.log(chalk.blue('Coding Beauty'));

If you can’t switch to an ES module environment, you can fix this by dynamically importing the module with the async import() function. For example:

index.js
// CommonJS module // ✅ Imports successfully const chalk = (await import('chalk')).default; console.log(chalk.blue('Coding Beauty'));

Or, you can downgrade to an earlier version of the package that supported CommonJS and require().

Shell
npm install chalk@4 # Yarn yarn add got@4

Here are the versions you should install for various well-known NPM packages to avoid this ERR_REQUIRE_ESM error:

Package versions for downgrading to fix the "Cannot use import statement outside a module" error in JavaScript.

Fix “Cannot use import statement outside a module” in TypeScript

If the module field in tsconfig.json is set to commonjs, any import statement in the TypeScript source will change to require() calls after the compilation and potentially cause this error.

tsconfig.json
{ //... "type": "module" }

Prevent this by setting module to esnext or nodenext

tsconfig.json
{ "type": "module" }

nodenext indicates to the TypeScript compiler that the project can emit files in either ESM or CommonJS format.

The secret trick Google uses to track everything you search online

Google now has at least 3 solid ways to track your search clicks and visits.

Have you ever tried to copy a URL directly from Google Search?

When I did that a few months ago, I unexpectedly got something like this from my clipboard.

Plain text
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjUmK2Tk-eCAxXtV0EAHX3jCyoQFnoECAkQAQ&url=https%3A%2F%2Fwww.codingbeautydev.com%2Fblog%2Fvscode-tips-tricks&usg=AOvVaw0xw4tT2wWNUxkHWf90XadI&opi=89978449

In my curiosity, I visited the page, and it took me straight to the URL I originally wanted.

This cryptic URL turned out to be a middleman that would redirect you to the actual page.

But what for?

After some investigation, I discovered that this was how Google Search had been recording our clicks and tracking every single visited page.

They set custom data- attributes and a mousedown event on each link in the search results page:

HTML
<a jsname="UWckNb" href="https://www.codingbeautydev.com/blog/vscode-tips-tricks" data-jsarwt="1" data-usg="AOvVaw0xw4tT2wWNUxkHWf90XadI" data-ved="2ahUKEwjUmK2Tk-eCAxXtV0EAHX3jCyoQFnoECAkQAQ">

A JavaScript function would change the href to a new URL with several parameters including the original URL, as soon as you start clicking on it.

JavaScript
import express from 'express'; const app = express(); app.get('/url', (req, res) => { // Record click and stuff... res.redirect(req.query); }); app.listen(3000);

So even though the browser would show the actual URL at the bottom-left on hover, once you clicked on it to copy, the href would change instantly.

Why mousedown over click? Probably because there won’t be a click event when users open the link in a new tab, which is something that happens quite often.

And so after right-clicking to copy like I did, mousedown would fire and the href would change, which would even update that preview URL at the bottom-left.

The new www.google.com/url page would log the visit and move out of the way so fast you’d barely notice it — unless your internet moves at snail speed.

They use this data for tools like Google Analytics and Search Console so site owners can improve the quality of their search results and pages by analyzing click-rate — something probably also using as a Search ranking factor. Not to mention recording clicks on Search ads to rake all the billions of yearly ad revenue.

Google Search Console. Source: Search Console Discover report now includes Chrome data

But Google got smarter.

They realized this URL tracking method had a serious issue for a certain group. For their users with slower internet speeds, the annoying redirect technique added a non-trivial amount of delay to the request and increased bounce rate.

So they did something new.

Now, instead of that cryptic www.google.com/url stuff, you get… the same exact URL?

With the <a> ping attribute, they have now successfully moved their tracking behind the scenes.

The ping attribute specifies one or more URLs that will be notified when the user visits the link. When a user opens the link, the browser asynchronously sends a short HTTP POST request to the URLs in ping.

The keyword here is asynchronously — www.google.com/url quietly records the click in the background without ever notifying the user, avoiding the redirect and keeping the user experience clean.

Browsers don’t visually indicate the ping attribute in any way to the user, which appears to go against the specification

When the ping attribute is present, user agents should clearly indicate to the user that following the hyperlink will also cause secondary requests to be sent in the background, possibly including listing the actual target URLs.

HTML Standard (whatwg.org)

Not to mention a privacy concern, which is why browsers like Firefox refuse to enable this feature by default.

In Firefox Google sticks with the mousedown event approach:

There are many reasons not to disable JavaScript in 2023, but even if you do, Google will simply replace the href with a direct link to www.google.com/url.

HTML
<a href="/url?sa=t&source=web&rct=j&url=https://www.codingbeautydev.com/blog/vscode-tips-tricks...">10 essential VS Code tips and tricks for greater productivity</a>

So, there’s really no built-in way to avoid this mostly invisible tracking.

Even the analytics are highly beneficial for Google and site owners in improving result relevancy and site quality, as users we should be aware of the existence and implications of these tracking methods.

It raises important questions about online privacy and the control we have over our personal information. As technology continues to advance, it’s crucial to critically evaluate the trade-offs between convenience and privacy in our digital lives.

[SOLVED] “auth/unauthorized domain” error in Firebase Auth

In this article, we’re going to learn how to easily fix the “auth/unauthorized domain” error which happens in the Firebase Authentication Web SDK.

What causes “auth/unauthorized domain” error in Firebase?

The Firebase “domain is not authorized” error happens when you try to use an API from Firebase Auth in a domain that is not authorized by Firebase.

It may occur in the FirebaseUI, or in your browser console.

The “auth/unauthorized” Firebase error occurring in FirebaseUI.

How to fix “auth/unauthorized domain” error in Firebase

To fix the “Domain not authorized” error in Firebase Auth, go to the Firebase Authentication Authorized domains settings for your project, using this link: https://console.firebase.google.com/project/_/authentication/settings.

Or by following these steps from the Firebase Console for your project in this image:

An image with steps to go to the Firebase Authentication Authorized domains settings page.

Enter the new domain in the dialog that shows after clicking Add domain:

Enter the new domain to register it as an authorized domain in Firebase Authentication.

How to get URL query string parameters in Next.js

Query parameters are used to pass data from the URL to the web server or browser. They are essential for customizing user experiences, filtering data, and tracking user actions.

Displaying the URL query parameters in a Next.js app.

Let’s learn how to easily get the query string parameters from a URL in a Next.js app.

In this article

Get URL query params in Next.js App Router client component

To get the URL query string parameters in the Next.js app directory, use the useSearchParams() hook from next/navigation.

app/amazing-url/page.tsx
'use client'; import { useSearchParams } from 'next/navigation'; export default function Home() { const searchParams = useSearchParams(); const query = searchParams.get('q'); return ( <> Welcome to Coding Beauty <br /> <br /> Your query: <b>{query}</b> </> ); }

We need ‘use client’ to use useSearchParams()

Notice the 'use client' statement at the top.

It’s there because all components in the new app directory are server components by default, so we can’t use any client-side specific functionality like hooks and animations.

We’ll get an error if we try to do anything interactive with useSearchParams or other hooks like useEffect, because it’s a server environment.

Get URL query params in Next.js Pages Router component

To get the URL query string parameters in pages directory component, use the query property of the useRouter() hook, which comes from the next/router module:

pages/coding-tips.tsx
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Home() { const router = useRouter(); const greeting = router.query.greeting; return ( <> <Head> <title>Coding Tips | Coding Beauty</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.icon" /> </Head> <main> <h2>{greeting}</h2> <p>Appreciate the beauty of coding</p> </main> </> ); }

Get URL query params in Next.js middleware

To get the URL query string parameters in Next.js App or Pages Router middleware, use the request.nextUrl.searchParams property:

middleware.ts
import { NextResponse } from 'next/server'; import { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { const continueUrl = request.nextUrl.searchParams.get('continue')!; return NextResponse.redirect(continueUrl); }

Get URL query params in Next.js server component

To get the URL query params in a server component, se the URL as a header in middleware, then parse this URL in the server component to get the query string and parameters:

middleware.ts
import { NextResponse } from 'next/server'; import { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { const reqHeaders = new Headers(request.headers); // toLowerCase() to avoid 404 due to Next.js case-sensitivity const url = request.url.toLowerCase(); reqHeaders.set('x-url', url); return NextResponse.next({ request: { headers: reqHeaders, }, }); }
app/search/page.tsx
import { headers } from 'next/headers'; export default function Page() { const headerList = headers(); const url = headerList.get('x-url')!; const query = new URL(url).searchParams.get('q'); return ( <> <h2>Welcome to Coding Beauty.</h2> <p>Your query: {query}</p> </> ); }

Get URL query params in getServerSideProps()

To get the URL query string params in the Pages Router getServerSideProps() function, use the context.query property:

pages/random-lyrics.tsx
export async function getServerSideProps(context) { const { songId } = context.query; const res = await fetch(`https://api.example.com/lyrics?songId=${songId}`); const lyrics = await res.json(); return { props: { lyrics, }, }; } export default function LyricsPage({ lyrics }) { const { song, content } = lyrics; return ( <div> {song} lyrics<div>{content}</div> </div> ); }

Get URL query params in Next.js Pages Router API

To get the URL query string parameters in an API in the pages directory, use the request.query property:

pages/api/stock-prices.tsx
import type { NextApiRequest, NextApiResponse } from 'next'; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { name } = req.query; const stockRes = await fetch(`api.example.com/stock-prices?name=${name}`); const stockData = await stockRes.json(); res.status(200).json({ stockData }); }

Get URL query params in Next.js App Router API

To get the URL query string params in an API in the Next.js 13 app directory, use the request.nextUrl.searchParams property:

app/api/forecast/route.ts
import { NextRequest, NextResponse } from 'next/server'; const data = { 'new-york': { summary: 'sunny' } // ... } export async function GET(req: NextRequest) { const location = req.nextUrl.searchParams.get('location'); const weatherData = data[location]; return NextResponse.json({ weatherData }); }

[SOLVED] Could not find an option named “no-sound-null-safety” in Flutter

Are you experiencing the “Could not find an option named no-sound-null-safety” error in Flutter?

The "Could not find an option named no-sound-null-safety" occurring in VS Code.
The “Could not find an option named no-sound-null-safety” occurring in VS Code.

We’re going to learn how to easily fix it in this article.

What causes the “Could not find an option named no-sound-null-safety” error?

The “Could not find an option named no-sound-null-safety” happens in a newer Flutter project using Dart 3.0, because Dart no longer supports unsound null safety.

Unsound null safety was a special Dart/Flutter feature where there are no static checks to ensure that we don’t access nullable variables – variables that may be null.

It allowed developers to migrate their codebase to the default null safety gradually without breaking existing code that depended on null-unsafe libraries.

But from version 3.0 upwards, Dart only supports code using sound null safety.

Fix “Could not find an option named no-sound-null-safety” (general)

To fix the “Could not find an option no-sound-null-safety” Flutter error, remove the --no-sound-null-safety option in your flutter run command.

The "Could not find an option named no-sound-null-safety" occurring in the command line.

Fix “Could not find an option named no-sound-null-safety” in VS Code

To fix the error in Visual Studio Code remove the --no-sound-null-safety option in the Dart: Flutter Additional Args setting.

You can use the Ctrl + , keyboard shortcut to quickly open the Settings page.

This if statement alternative only works in JavaScript

I’m not one of those who go on screaming about how horrible if statements are — in many cases, they are simply the best choice out of all the ways to create control flow.

Yet there are lots of situations where a different construct will do a noticeably better job of expressing our code’s intent — something we can’t ignore as long we write code for humans. Not to mention lower verbosity and shorter code.

So, let’s look at some powerful if statement alternatives.

1. The AND (&&) operator

This one is unique to JavaScript.

We quickly go from this:

JavaScript
function visitSite(user) { if (user.isLoggedIn) { console.log(`You are ${user.name}`); } console.log('Welcome to Coding Beauty.'); }

To this:

JavaScript
function visitSite(user) { user.isLoggedIn && console.log(`You are ${user.name}`); console.log('Welcome to Coding Beauty.'); }

We’ve eradicated the nested and compacted the branching logic into a one-liner.

You want to use this when there’s an if but no matching else; especially when the if block has only one line.

Even if there are multiple lines you can abstract them into a separate function and apply && again. After all the console.log() in our example is an abstraction itself.

So this:

JavaScript
function visitSite(user) { if (user.isLoggedIn) { console.log(`Welcome back, ${user.name}!`); console.log( `Your last login was on ${user.lastLoginDate}` ); console.log(`Your account type is ${user.accountType}`); } console.log('Welcome to Coding Beauty.'); }

Transforms to this:

JavaScript
function visitSite(user) { user.loggedIn && handleUser(user); console.log('Welcome to Coding Beauty.'); } function handleUser(user) { console.log(`Welcome back, ${user.name}!`); console.log( `Your last login was on ${user.lastLoginDate}` ); console.log(`Your account type is ${user.accountType}`); }

2. Ternary operator

Ternary operators let us compact if-else statements into a one-liner.

They’re great if-else replacements when all conditional cases only involve assigning a value to the same variable.

Here’s an example:

JavaScript
let word; if (num === 7) { word = 'seven'; } else { word = 'unknown'; }

Even though the DRY principle isn’t a hard and fast rule, for this instance things will be much cleaner if we used ternaries to avoid writing the variable assignment twice:

JavaScript
const word = num === 7 ? 'seven' : 'unknown';

Now we can even use const to keep things immutable and pure.

Nested ternaries

And when we have 3 or more branches in the if-else statement or we nest ifs, the cleaner ternary replacement will contain inner ternaries.

So this:

JavaScript
const getNumWord = (num) => { if (num === 1) { return 'one'; } else if (num === 2) { return 'two'; } else if (num === 3) { return 'three'; } else if (num === 4) { return 'four'; } else return 'unknown'; };

Becomes:

JavaScript
const getNumWord = (num) => num === 1 ? 'one' : num === 2 ? 'two' : num === 3 ? 'three' : num === 4 ? 'four' : 'unkwown';

Some people do cry about nested ternaries though, arguing that they’re complicated and cryptic. But I think that’s more of a personal preference, or maybe poor formatting.

And it’s formatting, we have tools like Prettier that have been doing this job (and only this job) for centuries.

Formatting nested ternary operators in VS Code with Prettier.
Ever had code this badly formatted?

As long as there’s sufficient indentation you should have no problems with readability. If the branching gets much more complex than above you probably want to move some of the lower-level logic into preceding variables or tiny functions.

Speaking of readability, Prettier is changing their nested ternary style; they’ve come up with something quite unique.

The current style uses a clever combination of flat and tree-like nesting; adding further indentation for nested ternaries in the truthy branch, but keeping things flat for those in the in the falsy branch.

JavaScript
const animalName = pet.canSqueak() ? 'mouse' : pet.canBark() ? pet.isScary() ? 'wolf' // Only nests this because it's in the truthy section : 'dog' : pet.canMeow() ? 'cat' : pet.canSqueak() // Flat because it's in the falsy section ? 'mouse' : 'probably a bunny';

But very soon Prettier will format the above like this:

JavaScript
const animalName = pet.canSqueak() ? 'mouse' : pet.canBark() ? pet.isScary() ? 'wolf' : 'dog' : pet.canMeow() ? 'cat' : pet.canSqueak() ? 'mouse' : 'probably a bunny';

The main change is the ?‘s are all now at the ending of the same line of its ending, instead of the next one.

3. Switch statement

You will find this in C-style languages like Java, C#, and Dart — and it looks exactly the same in those languages with a few semantic differences.

If ternaries are best for generating output for one variable, then switch statements are best for processing input *from* one variable:

JavaScript
function processUserAction(action) { switch (action) { case 'play': // if (action === 'play') console.log('Playing the game...'); startGame({ mode: 'multiplayer' }); break; case 'pause': // else if (action === 'pause') console.log('Pausing the game...'); pauseGame(); break; case 'stop': console.log('Stopping the game...'); endGame(); goToMainMenu(); break; case 'cheat': console.log('Activating cheat mode...'); enableCheatMode(); break; default: // else console.log('Invalid action!'); break; } }

The unique power of switch statements comes from being able to omit the break at the end of each case and let execution “fallthrough” to the next case:

JavaScript
// Generate a random number between 1 and 6 to simulate rolling a dice const diceRoll = Math.floor(Math.random() * 6) + 1; console.log(`You rolled a ${diceRoll}!`); switch (diceRoll) { case 1: console.log('Oops, you rolled a one!'); console.log('You lose a turn.'); break; case 2: console.log( 'Two heads are better than one... sometimes' ); case 4: case 6: // else if (diceRoll === 2 || diceRoll === 4 || diceRoll === 6) console.log('Nice roll!'); console.log('You move forward two spaces.'); break; // ... default: console.log('Invalid dice roll.'); }

Most other languages with switch-case allow this, with the notable exception of C#.

4. Key-value object

Key-value objects let us declaratively map inputs to outputs.

JavaScript
const weatherActivities = { sunny: 'go to the beach', rainy: 'watch a movie at home', cloudy: 'take a walk in the park', snowy: 'build a snowman', }; const weather = 'sunny'; console.log(`Okay, so right now it's ${weather}.`); console.log(`Why don't you ${weatherActivities[weather]}?`);

I found this invaluable when creating screens in React Native apps – each with its own loading, error and success states. Here’s a snippet of a screen in one of our apps:

JavaScript
// screens/course-list.tsx // ... import { ActivityIndicator, Text // ... } from 'react-native-paper'; type ViewState = 'loading' | 'error' | 'data'; export function Courses({ route, navigation }) { const [viewState, setViewState] = useState<ViewState>('loading'); const state = useAppState(); const courses = state?.courseList; // ... const contentDict = { loading: <ActivityIndicator />, error: <Text>Error</Text>, data: <CourseList courses={courses} />, }; const content = contentDict[viewState]; return ( <View> <StatusBar /> {content} </View> ); } // ...

Final thoughts

So if statements aren’t bad at all and are great for writing conditional logic in an easily understandable way. But it’s important to consider alternative approaches to make code shorter, clearer and even more expressive. It’s not about eliminating if statements entirely, but rather adopting effective techniques that make our code more efficient and elegant.