1

I need a simple and short one liner to set, check, and possible use the return of a function.

The multi-liner issue is this...

var x = somelongwindedfunctionthatshouldnotbeusedmorethanonce();
if (x) console.log(x);

What I want to avoid:

if (somelongwindedfunctionthatshouldnotbeusedmorethanonce()) {
console.log(somelongwindedfunctionthatshouldnotbeusedmorethanonce()) };

Basically put, I only want to run the console.log IF there is a valid value.
If it is null or empty, then don't run it.
If it has a valid value, then use that function's value in the console.log to print it.

I'd like to avoid having to use or declare a variable. I'm open to arrow functions or anonymous functions, so long as it is short and neat and only uses the long-winded-function only once.

The function of console.log() is only a red herring example, I need this to work with any function.

Any genius ideas on how to one-liner check the variable before using it?
Ternary doesn't work, as I do not wish to set a variable. Only to check the output of a function before putting it into another function.

Help Please, thanks.

Steve S
  • 69
  • 7
  • 3
    Something like `(x => x && console.log(x))(somelongfunctionname());` ? – blex Jan 24 '21 at 00:11
  • 1
    I think that works, can you post your answer so I can ask questions and/or vote on it? – Steve S Jan 24 '21 at 00:21
  • Just wanted to say, I've used this function many times in my program and find it one of the most useful things so far... thank you very much. I would up your solution, but apparently I do not have enough reputation at the moment. I'll certainly come back later though once I have it. – Steve S May 16 '21 at 16:36

2 Answers2

0

You could add a callback function, as a parameter, so like include this inside the function, and you don't even need to return anything.

function somelongwindedfunctionthatshouldnotbeusedmorethanonce(callback) {
  let returnValue = 1;
  if (returnValue) callback();
}
Timothy Chen
  • 431
  • 3
  • 8
0

You could create an IIFE and use short-circuit evaluation thanks to && (if the first condition does not pass, the rest won't be evaluated):

(x => x && console.log(x))(somelongfunctionname());
blex
  • 24,941
  • 5
  • 39
  • 72
  • 1
    I've tested it, and it works perfectly. Thank you, and thank you for providing an explanation. It looks very similar to what I'd been trying to work on for the past hour now with arrow functions, but I never heard of the IIFE with short-circuit evaluation, so I couldn't get to 2nd base. I voted you up, but apparently my reputation isn't 15+, so it won't show. – Steve S Jan 24 '21 at 00:39
  • Consider using [`??`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) rather than `&&` if you want to treat falsy values (such as `0`, `""`, or `false`) as valid return values. – Cat Jan 24 '21 at 00:59