I am looking for a way to code one-liner arrow functions that do not return any value. For example:
const fun = x => {
console.log(x);
};
I would remove the curly braces. Is it possible?
I am looking for a way to code one-liner arrow functions that do not return any value. For example:
const fun = x => {
console.log(x);
};
I would remove the curly braces. Is it possible?
4
Answers
You can do it by using the
void
operatorThis can be used if you want to run side effect without returning the value
For example:
voidFunc
will always returnundefined
and the side effect will still be called without the curly braceswithout curly braces it will be return the value
with curly brace need to add return
Sure, just remove the braces, since
console.log
does not return anything itself:The result is
undefined
, just as with the braces and noreturn
statement.If you have a single-expression body whose result value you want to suppress, you can also use the
void
operator:If you want to be funky you can have several statements in your arrow function without braces:
+
. all of your statements will be executed since+
doesn’t care about the operands (I sometimes use+
for a couple of small statements when the return value isn’t important).- 'x'
to have itNaN
|| undefined
to returnundefined
explicitly that would be equal to returning no valueAgain that’s crazy, just for stackoverflow snippet one-liners only 🙂
You could use
void
, looks cleaner, but I don’t like extra braces: