JavaScript noop
When I was starting with JavaScript, I'd see functions called noop
(it means no operation).
And then I'd look at the code and it would be something like:
function noop() {}
or something like
const noop = () => {};
The code is doing nothing! This function is useless right? Not necessarily.
The main use case is when a function accepts another function as an argument:
function fn(callback) {
callback();
// do something else...
}
// No operation. Does nothing.
function noop() {}
const cycles = 1e9; // 1 billion, 1 followed by 9 zeroes.
for (let i = 0; i < cycles; i++) {
fn(noop);
}
You might still be thinking it's useless. You could've done it like this:
function fn(callback) {
callback();
// do something else...
}
for (let i = 0; i < 1e9; i++) {
fn(function () {});
}
The problem is the performance. This version will create a new function a
billion times while the version with noop
will create one function and reuse that function every time.
If it's used a lot, it's much faster.
Check this interesting commit when jQuery make noop
an official part of the
library: jQuery commit.
Personally, I also consider more readable having a function named noop
instead
of an anonymous function.
Questions
Which option is the most efficient?
const noop = () => {};
function f(cb) {
cb();
}
// Option 1
for (let i = 0; i < 1e9; i++) f(() => {});
// Option 2
for (let i = 0; i < 1e9; i++) f(noop);
Which option is the most efficient?
function noop() {}
function f(cb) {
cb();
}
// Option 1
for (let i = 0; i < 1e9; i++) f(noop);
// Option 2
for (let i = 0; i < 1e9; i++) f(function () {});