Notable Nuances in JavaScript- 01

Notable Nuances in JavaScript- 01

This short read highlights some features that may not be majorly used

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
))

2. The Comma Operator

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

3. The nullish coalescing operator (??)

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 in part-02

(Read less, but effective )


You figure it out after spending quite a few nights

To view or add a comment, sign in

More articles by Deep B

  • Embracing SOLID Principles in Apex: A Guide for Salesforce Developers

    Salesforce development often involves creating robust and scalable solutions to meet the dynamic needs of businesses…

    1 Comment
  • Iterable Batch Apex

    Let’s traverse through data! The Database.Batchable interface contains three methods that must be implemented.

  • Efficient SOQL queries

    If you’re doing development in an org with a Large Data Volume then you must be careful with SOQL For best performance,…

  • Dive into : Database.Stateful

    We know that in Salesforce we have a powerful way to execute things in bulk using Batch Apex . But seldom we arrive in…

Explore content categories