skip to Main Content

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


  1. You can do it by using the void operator

    This can be used if you want to run side effect without returning the value

    For example:

    const sideEffectAndReturn = () => {
      console.log('side effect')
    
      return 10
    }
    
    const voidFunc = () => void sideEffectAndReturn()
    
    const returnValue = voidFunc()
    
    console.log({
      returnValue
    })

    voidFunc will always return undefined and the side effect will still be called without the curly braces

    Login or Signup to reply.
  2. without curly braces it will be return the value

    const fun = x => x;
    console.log(fun(1));
    

    with curly brace need to add return

    const fun1 = x => {
      return x;
    };
    console.log(fun1(2));
    
    Login or Signup to reply.
  3. Sure, just remove the braces, since console.log does not return anything itself:

    const fun = x => console.log(x);
    

    The result is undefined, just as with the braces and no return statement.

    If you have a single-expression body whose result value you want to suppress, you can also use the void operator:

    const fun = x => void console.log(x);
    
    Login or Signup to reply.
  4. If you want to be funky you can have several statements in your arrow function without braces:

    • join your statements with +. 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).
    • in the end you could have any result, add - 'x' to have it NaN
    • add || undefined to return undefined explicitly that would be equal to returning no value

    Again that’s crazy, just for stackoverflow snippet one-liners only 🙂

    const func = x => console.log('creating DIV with text:', x) + (document.body.appendChild(document.createElement('div')).textContent = x) - 'x' || undefined;
    
    console.log(func('some test text'));

    You could use void, looks cleaner, but I don’t like extra braces:

    const func = x => void (console.log('creating DIV with text:', x) + (document.body.appendChild(document.createElement('div')).textContent = x));
    
    console.log(func('some test text'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search