Notable Nuances in JavaScript- 01

This article highlights some features that may not be majorly used or known

  1. Replace can accept a callback function

The replace() command in JavaScript has a callback that provides you with some more information such as the matched content, the index, and the original string. What you return in that callback will be replaced to the matched content.

This allows you to enable a more complicated replacement, for example: you want to replace just the second occurrence of the letter "a" in "abcabc"to the letter "$".

How would you write a regex for that? What if we change the requirement
to any nth occurrence? Even if you find a regex solution, it won’t be elegant enough.

The syntax is:

String.prototype.replace(regExp, callback(
fullMatch: string,
...capturedMatches: string[],
positionOfFullMatchInString: number,
inputString: string
))

The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.

Here’s a version of a fibonacci generator, using the comma operator:

for (
var i=2, r=[0,1];
i<15;
r.push(r[i-1] + r[i-2]), i++
);


r //0,1,1,2,3,5,8,13,21,34,55,89,144,233,377

The nullish coalescing operator is written as two question marks ??.

The result of a ?? b is:

  • if a is defined, then a,
  • if a isn’t defined, then b.

In other words, ?? returns the first argument if it’s not null/undefined. Otherwise, the second one.

let height = 0;

alert(height || 100); // 100

alert(height ?? 100); // 0

(Note: Not Supported in old browsers)

Browser that supports are :

  • Google Chrome 80
  • Firefox 72

More To be Continued…

Developer and part time tech blogger