Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for empty function in Node.js

In JS, there is shorthand for an empty object which is {}. Is there shorthand for an empty function in JS?

The reason being, as functions are first-class objects, we use them as arguments more often, but passing in an empty function is at best ugly.

var foo = baz(function(){}); 

In order to declare a function, at somepoint we have to declare function(){}.

I would like more Node.js APIs to require a (callback) function to be passed, so the API doesn't deceivingly look synchronous. Perhaps one step in that direction would be to create shorthand for empty placeholder functions.

like image 765
Alexander Mills Avatar asked Jun 02 '15 00:06

Alexander Mills


People also ask

What is empty function in JS?

The empty statement is a semicolon ( ; ) indicating that no statement will be executed, even if JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one.

Is empty in JS?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.

How do you do nothing in JavaScript?

Use Void(0) to Define Do Nothing to Keep User on the Same Page in JavaScript. First, we'll use the void operator in a situation when you need an undefined result. However, void(0) tells JavaScript to DO NOTHING and RETURN NOTHING.


2 Answers

No, there is not. With ES6, you might be able to use an arrow function: ()=>{} which is a bit shorter.

If you really need this very often (you shouldn't?!), you can declare one yourself:

function noop(){} 

and then refer to that repeatedly. If you don't want to clutter your scope, you can also use the Function.prototype function (sic!) which does nothing but constantly return undefined - yet that's actually longer than your function expression.

like image 117
Bergi Avatar answered Oct 08 '22 09:10

Bergi


ES6 one could be:

   const noop = () => {}; 

Be careful if using Babel as it compiles differently - instead you can explicitly return something:

   const noop = () => ({}); 

See this tweet as to why the curly braces are important: https://twitter.com/_ericelliott/status/601420050327711744?lang=en

like image 44
sidonaldson Avatar answered Oct 08 '22 10:10

sidonaldson