javascript

The 5 most transformative JavaScript features from ES14

JavaScript has come a long way in the past 10 years with brand new feature upgrades in each one.

Still remember when we created classes like this?

JavaScript
function Car(make, model) { this.make = make; this.model = model; } // And had to join strings like this Car.prototype.drive = function() { console.log("Vroom! This " + this.make + " " + this.model + " is driving!"); };

Yeah, a lot has changed!

Let’s take a look at the 5 most significant features that arrived in ES14 (2023); and see the ones you missed.

1. toSorted()

Sweet syntactic sugar.

ES14’s toSorted() method made it easier to sort an array and return a copy without mutation.

Instead of this:

JavaScript
const nums = [5, 2, 6, 3, 1, 7, 4]; const sorted = clone.sort(); console.log(sorted); // [1, 2, 3, 4, 5, 6, 7] // ❌❌ Mutated console.log(nums); // [1, 2, 3, 4, 5, 6, 7]

We now got to do this βœ…:

JavaScript
const nums = [5, 2, 6, 3, 1, 7, 4]; // βœ… toSorted() prevents mutation const sorted = nums.toSorted(); console.log(sorted); // [1, 2, 3, 4, 5, 6, 7] console.log(nums); // [5, 2, 6, 3, 1, 7, 4]

toSorted() takes a callback for controlling sorting behavior – ascending or descending, alphabetical or numeric. Just like sort().

2. Array find from last

Searching from the first item isn’t always ideal:

JavaScript
const tasks = [ { date: '2017-03-05', name: 'πŸ‘Ÿrun a 5k' }, { date: '2017-03-04', name: 'πŸ‹οΈlift 100kg' }, { date: '2017-03-04', name: '🎢write a song' }, // 10 million records... { date: '2024-04-24', name: 'πŸ›οΈfinally sleep on time' }, { date: '2024-04-24', name: 'πŸ“1h writing with no breaks' }, ]; const found = tasks.find((item) => item.date === '2024-03-25'); const foundIndex = tasks.findIndex((item) => item.date === '2024-03-25'); console.log(found); // { value: '2024-03-25', name: 'do 1000 pushups' } console.log(foundIndex); // 9,874,910

You can easily see that it’ll be much faster for me to search our gigantic list from the end instead of start.

JavaScript
const tasks = [ { date: '2017-03-05', name: 'run a 5k' }, { date: '2017-03-04', name: 'lift 100kg' }, { date: '2017-03-04', name: 'write a song' }, // 10 million records... { date: '2024-04-24', name: 'finally sleep on time' }, { date: '2024-04-24', name: '1h writing with no breaks' }, ]; // βœ… Much faster const found = tasks.findLast((item) => item.date === '2024-03-25'); const foundIndex = tasks.findLastIndex((item) => item.date === '2024-03-25'); console.log(found); // { value: '2024-03-25', name: 'do 1000 pushups' } console.log(foundIndex); // 9,874,910

And they’re also times you MUST search from the end for your program work.

Like we want to find the last even number in a list of numbers, find and findIndex will be incredibly off.

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

And calling reverse() won’t work either, even as slow as it would be:

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

So in cases like where the findLast() and findLastIndex() methods come in handy.

JavaScript
const nums = [7, 14, 3, 8, 10, 9]; // βœ… Search from end const lastEven = nums.findLast((num) => num % 2 === 0); // βœ… Maintain proper indexes 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.

3. toReversed()

Another new Array method to promote immutability and functional programming.

Before – with reverse() ❌:

JavaScript
const arr = [5, 4, 3, 2, 1]; const reversed = arr.reverse(); console.log(reversed); // [1, 2, 3, 4, 5] // ❌ Original modified console.log(arr); // [1, 2, 3, 4, 5]

Now – with toReversed() βœ…:

JavaScript
const arr = [5, 4, 3, 2, 1]; const reversed = arr.toReversed(); console.log(reversed); // [1, 2, 3, 4, 5] // βœ… No modification console.log(arr); // [5, 4, 3, 2, 1]

I find these immutable methods awesome for constantly chaining methods over and over without worrying about the original variables:

JavaScript
// βœ… Results are independent of each other const nums = [5, 2, 6, 3, 1, 7, 4]; const result = nums .toSorted() .toReversed() .map((n) => n * 2) .join(); console.log(result); // 14,12,10,8,6,4,2 const result2 = nums .map((n) => 1 / n) .toSorted() .map((n) => n.toFixed(2)) .toReversed(); console.log(result2); // [ '1.00', '0.50', '0.33', '0.25', // '0.20', '0.17', '0.14' ]

4. toSpliced()

Lovers of functional programming will no doubt be pleased with all these new Array methods.

This is the immutable counterpart of .splice():

JavaScript
const colors = ['redπŸ”΄', 'purple🟣', 'orange🟠', 'yellow🟑']; // Remove 2 items from index 1 and replace with 2 new items const spliced = colors.toSpliced(1, 2, 'blueπŸ”΅', 'green🟒'); console.log(spliced); // [ 'redπŸ”΄', 'blueπŸ”΅', 'green🟒', 'yellow🟑' ] // Original not modified console.log(colors); // ['redπŸ”΄', 'purple🟣', 'orange🟠', 'yellow🟑'];

5. Array with() method

with() is our way of quickly change an array element with no mutation whatsoever.

Instead of this usual way:

JavaScript
const arr = [5, 4, 7, 2, 1] // Mutates array to change element arr[2] = 3; console.log(arr); // [5, 4, 3, 2, 1]

ES14 now let us do this:

JavaScript
const arr = [5, 4, 7, 2, 1]; const replaced = arr.with(2, 3); console.log(replaced); // [5, 4, 3, 2, 1] // Original not modified console.log(arr); // [5, 4, 7, 2, 1]

Final thoughts

They were other features but ES14 was all about easier functional programming and built-in immutability.

With the rise of React we’ve seen declarative JavaScript explode in popularity; it’s only natural that more of them come baked into the language as sweet syntactic sugar.

Shuffling algorithm in 1 line instead of 10: functional Fisher-Yates

Can we write the Fisher-Yates shuffling algorithm in a declarative and functional way with zero mutations, all in a single one-liner statement?!

Let’s find out.

The normal way of writing Fisher-Yates

Some time ago I was creating an indie card game for Android and I needed to shuffle the cards before sharing them to the user and opponents.

Well I didn’t know about the standard shuffling algorithms, so after some thought I came up with this:

But after reading more about Fisher-Yates on Wikipedia, I discovered serious problems with my algorithm:

JavaScript
// It was in C#, but like this function shuffleArray(array) { const clone = [...array]; for (let i = clone.length - 1; i > 0; i--) { // Swap i with random item from 0..n const randomIndex = Math.floor( Math.random() * clone.length // ❌❌ ); const temp = clone[i]; clone[i] = clone[randomIndex]; clone[randomIndex] = temp; } return clone; } console.log(shuffleArray(['C', 'I', 'O', 'L', 'G'])); // [ 'I', 'L', 'O', 'G', 'C' ] console.log(shuffleArray(['C', 'I', 'O', 'L', 'G'])); // [ 'L', 'O', 'G', 'I', 'C' ]

I was swapping each item with a random element in the range of 0..n, but this was wrong.

As explained here, this made it more likely for the array to get shuffled in particular ways.

The right way was to use the range 0..i to swap with the current element i in the loop.

JavaScript
function shuffleArray(array) { const clone = [...array]; for (let i = clone.length - 1; i > 0; i--) { const randomIndex = Math.floor(Math.random() * (i + 1)); const item = clone[i]; clone[i] = clone[randomIndex]; clone[randomIndex] = item; } return clone; } console.log(shuffleArray(['C', 'I', 'O', 'L', 'G'])); // [ 'G', 'L', 'I', 'C', 'O' ] console.log(shuffleArray(['C', 'I', 'O', 'L', 'G'])); // [ 'L', 'O', 'G', 'I', 'C' ]

With this I could make sure every possible shuffled result would have an equal chance of happening.

Functional, immutable, one-liner Fisher-Yates

How exactly are we supposed to go about this?

Can we try this?πŸ‘‡

JavaScript
const shuffleArray = (arr) => arr.reduce((array, item, i) => { const randomIndex = Math.floor( Math.random() * arr.length ); [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]]; return arr; });

No we can’t; We used ES6 swapping to shorten the code but we still mutated the array. And cloning doesn’t count.

We need to figure out a way to swap the array elements immutably – create a new array with items swapped.

Using conditionals we can easily come up with this:

JavaScript
const immutableSwap = (arr, i, j) => arr.map((item, index) => index === i ? arr[j] : index === j ? arr[i] : item ); const arr = ['B', 'E', 'A', 'U', 'T', 'Y']; console.log(immutableSwap(arr, 2, 4)); // [ 'B', 'E', 'T', 'U', 'A', 'Y' ]

But we could also use Object.values like this:

JavaScript
const immutableSwap = (arr, i, j) => { return Object.values({ ...arr, [i]: arr[j], [j]: arr[i], }); }; console.log(immutableSwap(arr, 3, 5)); // [ 'B', 'Y', 'A', 'U', 'T', 'E' ]

What’s next?

With the immutable swap worked out, our game plan is pretty straightforward:

  1. For each item i in 0..n, immutably select an index in 0..i to swap with i for each i in 0..n
  2. Loop through the array again and immutably swap each element with its assigned swapping pair.

For #1 we can easily use map() to create an array with the new random positions for every index:

JavaScript
const getShuffledPosition = (arr) => { return [...Array(arr.length)].map((_, i) => Math.floor(Math.random() * (i + 1)) ); }; /* [0, 2, 0, 1] swap item at: 1. index 0 with index 0 2. index 1 with index 2 3. index 2 with index 0 4. index 3 with index 1 */ getShuffledPosition(['πŸ”΅', 'πŸ”΄', '🟑', '🟒']); getShuffledPosition(['πŸ”΅', 'πŸ”΄', '🟑', '🟒']); // [0, 1, 1, 3] getShuffledPosition(['πŸ”΅', 'πŸ”΄', '🟑', '🟒']); // [0, 0, 2, 1]

What about #2?

We’re outputting an array, but we can’t use map again because the transformation at each step depends on the full array and not just the current element.

So we’ll use reduce():

JavaScript
const shuffleUsingPositions = (arr) => getShuffledPosition(arr).reduce( (toShuffle, newPosition, originalIndex) => immutableSwap(toShuffle, originalIndex, newPosition), arr ); shuffleUsingPositions(['πŸ”΅', 'πŸ”΄', '🟑', '🟒']) // [ 'πŸ”΄', 'πŸ”΅', '🟒', '🟑' ]

Not let’s de-abstract the immutable functions so we have a true and complete one-liner:

JavaScript
const shuffleArray = (arr) => [...Array(arr.length)] .map((_, i) => Math.floor(Math.random() * (i + 1))) .reduce( (toShuffle, newPosition, originalIndex) => toShuffle.map((item, index) => index === originalIndex ? toShuffle[newPosition] : item === newPosition ? originalIndex : item ), arr );

Or – faster and more readable:

JavaScript
const shuffleArray = (arr) => [...Array(arr.length)] .map((_, i) => Math.floor(Math.random() * (i + 1))) .reduce( (toShuffle, newPosition, originalIndex) => Object.values({ ...toShuffle, [originalIndex]: toShuffle[newPosition], [newPosition]: toShuffle[originalIndex], }), arr );
JavaScript
shuffleArray(['πŸ”΅', 'πŸ”΄', '🟑', '🟒']) // (3x) // [ '🟑', 'πŸ”΄', 'πŸ”΅', '🟒' ] // [ 'πŸ”΄', '🟑', '🟒', 'πŸ”΅' ] // [ '🟑', 'πŸ”΅', 'πŸ”΄', '🟒' ]

Just like you can always write a recursive algorithm as a loop, you can write every imperative iteration as a brilliant single-statement chain of array methods.

They all work perfectly.

VS Code: 5 rapid file creation tips for greater productivity

From painfully slow to lightning-fast, let’s look at all the 5 ways to create a file in VS Code.

And fastest way adds new files without having to use your mouse at all! We’ll see…

5. File > New File…

I’m pretty sure very few people use this apart from those who are new to text editors.

You move your mouse all the way up to File then click New File…

Then you’ve still got to enter the filename:

THEN, a file picker dialog for you to choose the folder – never mind VS Code having its own built-in file manager.

Before finally:

Create: New File

This is almost like the first, except you use the Create: New File from the Command Palette.

4. Double-click tab bar

Not many know about this method… double-clicking the file tab bar:

Ctrl + N

Or use the faster Ctrl + N keyboard shortcut.

So after Ctrl + N you either manually select a language:

Or you just start typing and wait for language auto-detection:

It’s useful when you don’t have any open project and you just want a quick file to work on.

You’re still got to save it though:

3. New File… icon button

This is one of the more popular ways; clicking the New File... icon button in the File Explorer Pane:

2. Double-click file explorer pane

This works great for top-level files.

1. A

Opening keyboard shortcuts like this:

And editing it like this:

To create files faster than ever at the single press of a key:

They all have different speeds but they’re all useful. VS Code’s vast versatility is unmatched.

17 lines of JS code became 1 line after this simple trick

How did these 17 lines of JavaScript code turn into a one-liner function?

It’s easy, you’ll see!

The 1st thing we notice is we’re selecting items from an array – this should NEVER take 3 lines in JavaScript!

We have the destructuring operator to turn this:

JavaScript
function extractRedirects(str) { const lines = str.split('\n'); const sourceDestinationList = []; for (const line of lines) { const sourceDestination = line.split(' '); const source = sourceDestination[2]; const destination = sourceDestination[3]; const redirectObj = { source: source, destination: destination, permanent: true, }; sourceDestinationList.push(redirectObj); } return sourceDestinationList; }

into this:

JavaScript
function extractRedirects(str) { const lines = str.split('\n'); const sourceDestinationList = []; for (const line of lines) { // βœ… Skip 1st two with comma placeholders! const [, , source, destination] = line.split(' '); const redirectObj = { source: source, destination: destination, permanent: true, }; sourceDestinationList.push(redirectObj); } return sourceDestinationList; }

What else is obvious? A loop and a gradual accumulation (with push).

Which means we’re easily cutting out statements here with map() or reduce():

reduce works well anywhere but map is the natural choice since 1 array clearly transforms to another here.

So we go from this:

JavaScript
function extractRedirects(str) { const lines = str.split('\n'); const sourceDestinationList = []; for (const line of lines) { const [, , source, destination] = line.split(' '); const redirectObj = { source: source, destination: destination, permanent: true, }; sourceDestinationList.push(redirectObj); } return sourceDestinationList; }

To this:

JavaScript
function extractRedirects(str) { const lines = str.split('\n'); const sourceDestinationList = lines.map((line) => { // βœ… const [, , source, destination] = line.split(' '); const redirectObj = { source: source, destination: destination, permanent: true, }; // βœ… return redirectObj; }); return sourceDestinationList; }

The declaration, for loop and push() have all been eradicated.

Now removing the temporary variable:

JavaScript
function extractRedirects(str) { const lines = str.split('\n'); const sourceDestinationList = lines.map((line) => { const [, , source, destination] = line.split(' '); return { source: source, destination: destination, permanent: true, }; }); return sourceDestinationList; }

And combining the last 2 statements in map‘s callback – without calling split() twice.

JavaScript
function extractRedirects(str) { const lines = str.split('\n'); const sourceDestinationList = lines.map((line) => { return line.split(' ').reduce( (acc, curr, i) => { return i === 2 ? { ...acc, source: curr } : i === 3 ? { ...acc, destination: curr } : acc; }, { permanent: true } ); }); return sourceDestinationList; }

reduce() has a way of making your head spin!

Let’s go with this instead; much more readable:

JavaScript
function extractRedirects(str) { const lines = str.split('\n'); const sourceDestinationList = lines .map((line) => { return line.split(' '); }) .map(([, , source, destination]) => { return { source: source, destination: destination, permanent: true, }; }); return sourceDestinationList; }

Now we can remove the callback braces, from (a) => { return { b; } } to (a) => ({ b }):

JavaScript
function extractRedirects(str) { const lines = str.split('\n'); const sourceDestinationList = lines .map((line) => line.split(' ')) .map(([, , source, destination]) => ({ source: source, destination: destination, permanent: true, })); return sourceDestinationList; }

All that’s left now is to remove the 2 remaining temp vars and use implicit property values:

JavaScript
function extractRedirects(str) { return str .split('\n') .map((line) => line.split(' ')) .map(([, , source, destination]) => ({ source, // βœ… destination, // βœ… permanent: true, })); }

Arrow function:

JavaScript
const extractRedirects = (str) => str .split('\n') .map((line) => line.split(' ')) .map(([, , source, destination]) => ({ source, destination, permanent: true, }));

Yes refactors are fun; it’s fun to see the function gradually evolve and grow in a compact one-liner form.

And it wasn’t just for fancy; With it I moved a GIGANTIC amount of redirect information…

From painful, dinosaur WP Apache .htaccess:

They were way more than 5!

To lovely, modern next.config.js

And it worked perfectly.

The 7 most transformative JavaScript features from ES10

JavaScript has come a long way in the past 10 years with brand new feature upgrades in each one.

Still remember when we created classes like this?

JavaScript
function Car(make, model) { this.make = make; this.model = model; } // And had to join strings like this Car.prototype.drive = function() { console.log("Vroom! This " + this.make + " " + this.model + " is driving!"); };

Yeah, a lot has changed!

Let’s take a look at the 7 most significant features that arrived in ES10 (2019); and see the ones you missed.

1. Modularization on the fly: Dynamic imports

The ES10 year was the awesome year when import could now act as function, like require(). An async function.

Keeping imports at the top-level was no longer a must; We could now easily resolve the module’s name at compile time.

Loading modules optionally and only when absolutely needed for high-flying performance…

JavaScript
async function asyncFunc() { if (condition) { const giganticModule = await import('./gigantic-module'); } }

Loading modules based on user or variable input…

JavaScript
import minimist from 'minimist'; const argv = minimist(process.argv.slice(2)); viewModule(argv.name); async function viewModule(name) { const module = await import(name); console.log(Object.keys(module)); }

It’s also great for using ES modules that no longer support require():

JavaScript
// ❌ require() of ES modules is not supported const chalk = require('chalk'); console.log(chalk.blue('Coding Beauty')); (async () => { // βœ… Runs successfully const chalk = (await import('chalk')).default; console.log(chalk.blue('Coding Beauty')); })();

2. Flattening the curve

flat() and flatMap() gave much cleaner ways to easily flatten multidimensional arrays.

Eradicating the need for painful array-looping flattening code:

JavaScript
const colorSwatches = [ 'cream🟑', ['scarletπŸ”΄', 'cherryπŸ”΄'], ['blueπŸ”·', ['sky blue🟦', 'navy blueπŸ”΅']], ]; // Default depth of 1 console.log(colorSwatches.flat()); // ['cream🟑', 'scarletπŸ”΄', 'cherryπŸ”΄', 'blueπŸ”·', // ['sky blue🟦', 'navy blueπŸ”΅']] console.log(colorSwatches.flat(2)); // ['cream🟑', 'scarletπŸ”΄', 'cherryπŸ”΄', 'blueπŸ”·', // 'sky blue🟦', 'navy blueπŸ”΅']

flatMap() is as good as calling map(), then flat(1):

JavaScript
const colorSwatches = [ 'cream🟑', ['scarletπŸ”΄', 'cherryπŸ”΄'], ['blueπŸ”·', ['sky blue🟦', 'navy blueπŸ”΅']], ]; // map to get only the emoji console.log( colorSwatches.flatMap((color) => Array.isArray(color) ? color : color.slice(-2) ) ); // [ '🟑', 'cherryπŸ”΄', 'blueπŸ”·', [ 'sky blue🟦', 'navy blueπŸ”΅' ] ]

3. Transform arrays to objects

ES10 was also when Object.fromEntries() arrived on the JavaScript scene.

Quickly convert list of key-value pairs to equivalent key-value object:

JavaScript
const entries = [ ['name', 'The Flash⚑'], ['realName', 'Barry Allen'], ['lightningColor', 'yellow🟑'], ['suitColor', 'redπŸ”΄'], ]; console.log(Object.fromEntries(entries)); /** { name: 'The Flash⚑', realName: 'Barry Allen', lightningColor: 'yellow🟑', suitColor: 'redπŸ”΄' } */

4. Clean up your strings with precisions

trimStart() and trimEnd().

Before now everyone was using trim from NPM – Happily adding 3.35KB to the project…

Even now:

But slowly losing popularity to .trim().

Then Array trim() came along, then trimStart() and trimEnd().

JavaScript
const fruits = ' pineapple🍍 '; console.log(fruits.trimStart()); // 'pineapple🍍 ' console.log(fruits.trimEnd()); // ' pineapple🍍' console.log(fruits.trim()); // 'pineapple🍍'

5. Catching errors without the baggage

With the new optional catch binding, you now safely omit the catch block’s error argument when you had nothing to do with it:

JavaScript
// ❌ Before ES10 try { iMayExplodeAnyMomentNow(); } catch (err) { // Or else error } // βœ… try { iMayExplodeAnyMomentNow(); } catch {}

6. Sorting without surprise

Stable Array sort.

Previously when sorting an array there was absolutely no way we could guarantee the arrangement of the equal elements.

But in the post-ES10 JS code here, we are 100% sure that react always comes before vue always comes before angular.

JavaScript
const geniusPortfolio = [ { tool: 'javascript', years: 2000, }, { tool: 'react', years: 1000 }, { tool: 'vue', years: 1000 }, { tool: 'angular', years: 1000 }, { tool: 'assembly', years: 7000 }, ]; const sortedDesc = geniusPortfolio.sort((a, b) => { return b.years - a.years; }); const sortedAsc = geniusPortfolio.sort((a, b) => { return a.years - b.years; });

7. Go big or go home: BigInts

The name BigInt gives it purpose away: For loading up on unbelievably humongous integer values:

JavaScript
const bigInt = 240389470239846028947208942742089724204872042n; const bigInt2 = BigInt( '34028974029641089471947861048917649816048962' ); console.log(typeof bigInt); console.log(bigInt); console.log(typeof bigInt2); console.log(bigInt2); console.log(bigInt * bigInt2);

Because normal integers can’t:

JavaScript
// βœ–οΈ Stored as double const normalInt = 240389470239846028947208942742089724204872042; const normalInt2 = 34028974029641089471947861048917649816048962; console.log(typeof normalInt); console.log(normalInt); console.log(typeof normalInt2); console.log(normalInt2); // βœ–οΈ Precision lost console.log(normalInt * normalInt2);

Final thoughts

ES10 marked a significant leap forward for JavaScript with several features that have become essential for modern development.

Use them write cleaner code with greater conciseness, expressiveness, and clarity.

New array slice notation in JavaScript – array[start:stop:step]

With this new slice notation you’ll stop writing code like this:

JavaScript
const decisions = [ 'maybe', 'HELL YEAH!', 'No.', 'never', 'are you fr', 'uh, okay?', 'never', 'let me think about it', ]; const some = decisions.slice(1, 4); console.log(some); // [ 'HELL YEAH!', 'No.', 'are you fr' ]

And start writing code like this:

JavaScript
const decisions = [ 'maybe', 'HELL YEAH!', 'No.', 'never', 'are you fr', 'uh, okay?', 'never', 'let me think about it', ]; const some = decisions[1:4]; console.log(some); // [ 'HELL YEAH!', 'No.', 'are you fr' ]

Much shorter, readable and intuitive.

And we don’t even have to wait till it officially arrivesβ€Šβ€”β€Šwe can have it right now.

By extending the Array class:

JavaScript
Array.prototype.r = function (str) { const [start, end] = str.split(':').map(Number); return this.slice(start, end); }
JavaScript
const decisions = [ 'maybe', 'HELL YEAH!', 'No.', 'never', 'are you fr', 'uh, okay?', 'never', 'let me think about it', ]; const some = decisions.r('1:4'); console.log(some); // [ 'HELL YEAH!', 'No.', 'are you fr' ]

Slice it right to the end

Will it slice to the last item if we leave out the second number?

JavaScript
Array.prototype.r = function (str) { const [start, end] = str.split(':').map(Number); return this.slice(start, end); }; const yumFruits = [ 'apple🍎', 'banana🍌', 'orange🍊', 'strawberryπŸ“', 'mangoπŸ₯­', ]; const some = yumFruits.r('1:'); console.log(some);

It doesn’t?

Because end is empty string and Number('') is 0, so we have arr.slice(n, 0) which is always an empty array.

Let’s upgrade r() with this new ability:

JavaScript
Array.prototype.r = function (str) { const [startStr, endStr] = str.split(':'); // πŸ‘‡ Slice from start too const start = startStr === '' ? 0 : Number(startStr); // βœ… const end = endStr === '' ? this.length : Number(endStr); // βœ… return this.slice(start, end); }; const yumFruits = [ 'apple🍎', 'banana🍌', 'orange🍊', 'strawberryπŸ“', 'mangoπŸ₯­', ]; console.log(yumFruits.r('1:')); console.log(yumFruits.r(':2')); console.log(yumFruits.r('1:3'));

Dealing with negativity

Can it handle negative indices?

JavaScript
const yumFruits = [ 'apple🍎', 'banana🍌', 'orange🍊', 'strawberryπŸ“', 'mangoπŸ₯­', ]; console.log(yumFruits.r(':-2')); console.log(yumFruits.r('2:-1'));

It surely can:

The negative start or end is passed straight to slice() which already has built-in support for them.

Start-stop-step

We upgrade again to array[start:stop:step] – step for jumping across the array in constant intervals.

Like we see in Python (again):

Plain text
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // Index 2 to 7, every 2 elements print(arr[2:7:2])

This time slice() has no built-in stepping support, so we use a good old for loop to quickly leap through the array.

JavaScript
Array.prototype.r = function (str) { const [startStr, endStr, stepStr] = str.split(':'); const start = startStr === '' ? 0 : Number(startStr); // βš’οΈ negative indexes const absStart = start < 0 ? this.length + start : start; const end = endStr === '' ? this.length : Number(endStr); const absEnd = end < 0 ? this.length + end : end; const step = stepStr === '' ? 1 : Number(stepStr); const result = []; for (let i = absStart; i < absEnd; i += step) { result.push(this[i]); } return result; }; const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; console.log(nums.r('2:7:2')); console.log(nums.r('8::1')); console.log(nums.r('-6::2')); console.log(nums.r('::3'));

Perfect:

Array reduce() does the exact same job elegant immutably.

I think there’s something about the function flow of data transformation that makes it elegant.

Readability

JavaScript
Array.prototype.r = function (str) { const [startStr, endStr, stepStr] = str.split(':'); const start = startStr === '' ? 0 : Number(startStr); const absStart = start < 0 ? this.length + start : start; const end = endStr === '' ? this.length : Number(endStr); const absEnd = end < 0 ? this.length + end : end; const step = stepStr === '' ? 1 : Number(stepStr); const result = this.reduce( ( acc, cur, index ) => index >= absStart && index < absEnd && (index - absStart) % step === 0 ? [...acc, cur] : acc, [] ); return result; };

Flip the script

What about stepping backwards?

Of course Python has it:

Plain text
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(arr[7:3:-1]) # [8, 7, 6, 5]

One thing you instantly notice here is start is greater than stop. This is a requirement for backward stepping.

Plain text
print(arr[3:7:-1]) # [] print(arr[7:3:1]) # []

Which makes sense: if you’re counting backwards you’re going from right to left so start should be more.

What do we do? Once again slice() does some of the heavy lifting for us…

We simply swap absStart and absEnd when step is negative

JavaScript
const [realStart, realEnd] = step > 0 ? [absStart, absEnd] : [absEnd, absStart]; // ❌ start > end (4:8), step: -1 -> (8:4) // βœ… end > start (7:3), step: -1 -> (3:7)

slice() returns an empty array when end > start:

JavaScript
const color = [ 'cream🟑', 'cobalt blueπŸ”΅', 'cherryπŸ”΄', 'celadon🟒', ]; console.log(color.slice(1, 3)); // [ 'cobalt blueπŸ”΅', 'cherryπŸ”΄' ] console.log(color.slice(3, 0)); // []

Now let’s combine everything together:

JavaScript
Array.prototype.r = function (str) { const [startStr, endStr, stepStr] = str.split(':'); const start = startStr === '' ? 0 : Number(startStr); const step = stepStr === '' ? 1 : Number(stepStr); const absStart = start < 0 ? this.length + start : start; // πŸ‘‡ count to start for empty end when step is negative const end = endStr === '' ? (step > 0 ? this.length : 0) : Number(endStr); const absEnd = end < 0 ? this.length + end : end; const [realStart, realEnd] = step > 0 ? [absStart, absEnd] : [absEnd, absStart]; const slice = this.slice(realStart, realEnd); // πŸ‘ˆ if (slice.length === 0) return []; // πŸ‘ˆ const result = []; // πŸ‘‡ for ( let i = absStart; step > 0 ? i < absEnd : i > absEnd; i += step ) { result.push(this[i]); } return result; }; const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; console.log(nums.r('2:7:2')); console.log(nums.r('-1:-7:-1')); console.log(nums.r('-7::-1')); console.log(nums.r('-5:9:-2')); console.log(nums.r('::3'));

We’ve come a long way! Remember how we started?

JavaScript
Array.prototype.r = function (str) { const [start, end] = str.split(':').map(Number); return this.slice(start, end); }

Yeah, and we didn’t even add any checks for wrong types and edge cases. And it goes without saying that I spent more than a few minutes debugging this…

And just imagine how it would be if we add multi-dimensional array support like in numpy:

JavaScript
import numpy as np sensor_data = np.array([ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]) temperatures = sensor_data[:, 1] print(temperatures) # [20 50 80]

But with our new Array r() method, we’ve successfully brought Python’s cool array slicing notation to JavaScript.

7 little-known console methods in JavaScript

There’s more to console methods than log error and warn.

Did you know they’re actually up to 20?

And they do way more than logging text: colorful🎨 data visualization, debuggingπŸ”Ž, performance⚑ testing and so much more.

Check out these powerful 7:

1. table()

console.table(): Easily display object array as table: one row per object; one col per prop.

JavaScript
const fruits = [ { name: 'Mango', ripeness: 10, sweetness: 'πŸ˜‹', }, { name: 'Banana', ripeness: 6, sweetness: '😏', }, { name: 'Watermelon', ripeness: 8, sweetness: 'πŸ€”', }, ]; console.table(fruits);

A bit different on Node:

Both clearly better than using console.log():

2. trace()

Where did we come from on the call stack? Let’s trace() our steps back!

Fantastic for debugging:

JavaScript
function coder() { goodCoder(); } function goodCoder() { greatCoder(); } function greatCoder() { greatSuperMegaGeniusCoder(); } function greatSuperMegaGeniusCoder() { console.log( "You only see the greatness now, but it wasn't always like this!" ); console.log( 'We\'ve been coding for generations -- let me show you...' ); console.trace(); } coder();

3. count()

console.count() logs the number of times that the current call to count() has been executed.

Too indirect and recursive a definition for me! You may need to see an example to really get it…

JavaScript
function shout(message) { console.count(); return message.toUpperCase() + '!!!'; } shout('hey'); shout('hi'); shout('hello');

console.count() has an internal counter starting at 0. After each call it increments the counter by 1 and logs it…

Much better.

Where did default come from? That’s the label for the counter. I’m guessing there’s an internal dictionary with a counter value for each label key.

console.count() has an internal counter starting at 0 for a new label. After each call it increments the counter by 1 and logs it…

We easily customize the label with the 1st argument to count().

JavaScript
function shout(message) { console.count(message); return message.toUpperCase() + '!!!'; } shout('hey'); shout('hi'); shout('hello'); shout('hi'); shout('hi'); shout('hello');

Now we have a different count for each message.

So countReset() obviously resets a label’s internal counter to 0.

JavaScript
function shout(message) { console.count(message); return message.toUpperCase() + '!!!'; } shout('hi'); shout('hello'); shout('hi'); shout('hi'); shout('hello'); console.log('resetting hi'); console.countReset('hi'); shout('hi');

4. clear()

CLS for JavaScript.

5. time() + timeLog() + timeEnd()

They work together to precisely measure how long a task takes.

57 microseconds, 11 seconds, 50 years? No problem.

  • time() – start the timer.
  • timeLog() – how far has it gone?
  • timeEnd() – stop the timer.

Let’s use them to compare the speed of all the famous JavaScript loop types.

JavaScript
console.time('for'); for (let i; i < 1000; i++) { for (let i = 0; i < arr.length; i++); } console.timeLog('for'); for (let i; i < 1000000; i++) { for (let i = 0; i < arr.length; i++); } console.timeEnd('for'); const arr1000 = [...Array(1000)]; const arr1000000 = [...Array(1000000)]; console.time('for of'); for (const item of arr1000); console.timeLog('for of'); for (const item of arr1000000); console.timeEnd('for of'); console.time('forEach'); arr1000.forEach(() => {}); console.timeLog('forEach'); arr1000000.forEach(() => {}); console.timeEnd('forEach');

for starts out slow but it destroys the other as the list grows…

6. group() + groupCollapsed() + groupEnd()

Another great combo for grouping a bunch of console messages together; visually with indentation and functionally with a UI expander.

  • group() – adds 1 further grouping level.
  • groupCollapsed() – like group() but group starts out collapsed.
  • groupEnd() – go back to previous grouping level.
JavaScript
console.log('What can we do?'); console.group('Abilities'); console.log('RunπŸ‘Ÿ - solid HIIT stuff'); console.groupCollapsed('CodeπŸ’»'); console.log('JavaScript'); console.log('Python'); console.log('etc of course'); console.groupEnd(); console.log('EatπŸ‰ - not junk tho...');

Just indentation on Node – so groupCollapsed() has no use here.

7. dir()

dir() is a genius way to inspect an object in the console and see ALL it’s properties and methods.

Actually just like console.log()? πŸ€” But console.dir() is specially designed for this particular purpose.

But watch what happens when you log() vs dir() HTML element objects:

log() shows it as a HTML tag hierarchy, but dir() shows it as an object with every single property it has and could ever dream of having.

Final thoughts

So they’re plenty of console methods apart from console.log(). Some of them spice things up in the console UI with better visualization; others are formidable tools for debugging and performance testing.

Never use magic numbers in your code: Do this instead

You can never guess what this does πŸ‘‡

JavaScript
function c(a) { return a / 13490190; } const b = c(40075); console.log(p); // 0.002970677210624906

All we see is a calculation. We have no idea what those numbers and variables mean in the bigger picture of the codebase.

It’s a mystery. It’s magic to everyone apart from the developer who wrote the code.

We can’t possibly make any contributions to this code; we’re stuck.

But what if our dev had looked beyond code that merely works and also focused on communicating the full story of the code?

At the very least they would have given those variables far more descriptive names to explain the context:

JavaScript
function calculateSpeedstersTime(distance) { return distance / 13490190; } const time = calculateSpeedstersTime(40075); console.log(time); // 0.002970677210624906

This small change vastly improves the code’s readability. Now you have a general idea of what’s going on.

But there are still mysteries we must solve.

It’ll still take us a little bit to realize 13490190 is speed — but how much speed?. And we know 40075 is a distance, but why 40075 of all the numbers?

For maximum readability we replace these magic numbers with variables with explanatory names

JavaScript
const speedstersSpeedKmPerHr = 13490190; const earthCircumferenceKm = 40075; function calculateSpeedstersTime(distance) { return distance / speedstersSpeedKmPerHr; } const time = calculateSpeedstersTime(earthCircumferenceKm); console.log(time); // 0.002970677210624906 ~ 11s

Now you understand every single thing this code does at a glance.

Understanding at a glance is always the goal.

Even with readable code…

Anyone can understand this TS code here; but there’s a serious issue that could easily lead us to hours-long bug hunting.

Can you spot it?

JavaScript
class Person { state: string; name: string; greet() { console.log(`Hey I'm ${this.name}`); } eatFood() { if (this.state === 'tired') { this.state = 'fresh'; } } exercise() { if (this.state === 'fresh') { this.state = 'tired'; } } }

Problem: We’re lousily checking the state for equality and assigning with magic strings again and again.

Repeating ourselves, and allow a mere typo to break this code in the future. And the bug won’t always be easy to spot like it would be in this tiny code.

That’s why we have union types; similar to enums in TypeScript and other languages.

JavaScript
class Person { name: string; // βœ… Only 3 values, not infinite state: 'tired' | 'fresh' | 'sleepy'; greet() { console.log(`Hey I'm ${this.name}`); } eatFood() { if (this.state === 'tired') { this.state = 'fresh'; } } exercise() { // βœ… Typo: Error thrown if (this.state === 'fres') { this.state = 'tired'; } } }

Now 'tired' and 'fresh' are no longer random string literals. They’re now registered values of a pre-defined type.

And this is one of the powerful advantages TypeScript has over regular JS.

We even have this exact type of issue in a Dart codebase I’m part of. We’ve used the same magic strings like 10 times each.

But Dart only has enums and it’s not so easy to convert from magic strings to enums like we did here with union types. So we better refactor before it comes back to bite us!

The only thing that remains constant…

Keep using magic values and they keep spreading throughout the codebase across more and more files.

Replacing them is a chore.

JavaScript
// email.js export function sendEmail({ username }) { emailApi.send({ title: `Hi ${username ?? 'User'}`, role: 'user' // Union type value }); } // user-info.jsx export function UserInfo({ user }) { return ( <div> <div>Name: {user.name ?? 'User'}</div> <div>Email: {user.email}</div> </div> ); }

What happens when you want to change the default user name to something else but you’ve got the 'User' magic string in over 15 files?

Even Find and Replace will be tricky because they could be other strings with the same value but no relation.

We can fix this issue by creating a separate global config file containing app-wide values like this:

JavaScript
// app-values.js export const DEFAULT_USERNAME = 'User'; // βœ… Only one place to change // email.js import { DEFAULT_USERNAME } from './app-values'; export function sendEmail({ username, role }) { emailApi.send({ message: `Hi ${username ?? DEFAULT_USERNAME}`, // βœ… role: role ?? 'user', }); } // user-info.jsx import { DEFAULT_USERNAME } from './app-values'; export default function UserInfo({ user }) { return ( <div> <div>Name: {user.name ?? DEFAULT_USERNAME}</div> // βœ… <div>Email: {user.email}</div> </div> ); }

Final thoughts

Banish magic numbers and strings from your JavaScript code for clarity, maintainability, and efficiency.

By adopting these practices you pave the way for code that is not only functional but also self-documenting, collaborative, and resilient in the face of change.

3 ways to show line breaks in HTML without ever using br

Of course <br/> is what we all grew up with from our HTML beginnings, but there’s more.

Like… CSS white-space: pre-wrap:

HTML
<div id="box"> Coding is cognitively demanding, mentally stimulating, emotionally rewarding, beauty, unity power </div>
CSS
#box { background-color: #e0e0e0; width: 250px; font-family: Arial; white-space: pre-wrap; }

Without pre-wrap:

pre-wrap preserves line breaks and sequences of whitespace in the element’s text.

So the 4 spaces between the words in the first line are shown in the output along with the line break.

Even the space used for text indentation is also shown in the output, adding extra left padding to the container.

JS too

pre-wrap also acknowledges the \n character when set from JavaScript; with innerText or innerHTML:

JavaScript
const box = document.getElementById('box'); box.innerText = 'Coding is \n logic, art, growth, \n creation';

Without pre-wrap:

pre

pre works a lot like pre-wrap but no more auto wrapping:

For example:

HTML
<div id="box"> JavaScript at Coding Beauty HTML at Coding Beauty CSS at Coding Beauty </div>
CSS
#box { white-space: pre; background-color: #e0e0e0; width: 250px; font-family: Arial; }

If pre was pre-wrap in this example:

The behavior with pre is the same when you set the innerHTML or innerText property of the element to a string using JavaScript.

Newlines only

white-space:pre-line: Ignore extra spaces but show line breaks:

HTML
<div id="box"> Coding is growth unity power beauty </div>
CSS
#box { background-color: #e0e0e0; width: 250px; font-family: Arial; white-space: pre-line }

pre-line -> pre-wrap:

Like the previous two possible white-space values, pre-line works in the same way when you set the innerHTML or innerText property of the element to a string using JavaScript.

Master JavaScript Mutation Observer: amazing real-world use cases

JavaScript Mutation Observer.

An underrated API for watching for changes in the DOM: “child added”, “attribute changed”, and more.

JavaScript
// Node/element to be observed for mutations const targetNode = document.getElementById('my-el'); // Options for the observer (which mutations to observe) const config = { attributes: true, childList: true, subtree: true }; // Callback function to execute when mutations are observed const callback = (mutationList, observer) => { for (const mutation of mutationList) { if (mutation.type === 'childList') { console.log('A child node has been added or removed.'); } else if (mutation.type === 'attributes') { console.log( `The ${mutation.attributeName} attribute was modified.` ); } } }; // Create an observer instance linked to the callback function const observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(targetNode, config); // Later, you can stop observing observer.disconnect();

I see a bunch of people online curious to know the point of this API in the real-world.

In this post I’ll show you how I used it to easily shut-up this annoying script carrying out unwanted activities on the page.

And you’ll see how sleek and polish the UI elements became after this.

The 3rd party script

It came from Mailchimp – a service for managing email lists.

Mailchimp provides embedded forms to easily collect sign-ups to your list.

These forms are HTML code embedded in your webpage without any additional configuration.

But being this ready-to-use nature comes at a cost; deeply embedded CSS stubbornly resisting any attempt to customize the form’s look and feel.

I mean I know I definitely spent WAY more than I should have doing this, having to throw CSS !important all over the place and all…

Stubbornly rigid JS

On the JS side I had the remote Mailchimp script showing these pre-defined error/success messages after the request to the Mailchimp API.

Sure this was an decent success message but there was simply no built-in option to customize it. And we couldn’t indicate success in other ways like a color or icon change.

Mutation Observer to the rescue…

Waiting for the precise moment the success text came in and instantly swapping out the copy for whatever I wanted and doing anything else.

And just like that the script was blocked from directly affecting the UI.

We basically turned it into an Event Emitter service; an observable.

This let us easily abstract everything into a React component and add various event listeners (like onSuccess and onError):

To create the polished form we saw earlier:

This is the power of the JavaScript Mutation Observer API.