1

Can you do a boolean check and assignment in the same line?

i.e. if I have a function that could return a value or could return null..

const someFunc = () => {
  if (someCondition) return null;
  return 'Hello, world';
}

And I want to use that value in another function but only if it's not null then I can do this...

const someOtherFunction = () => {
  let value = someFunc();
  if (!value) return;

  // do something
}

Can I wrap these two lines into a single "assign and verify" check like...

if (let value = someFunc()) {
  // do something
}

Or something like that?

Fogmeister
  • 76,236
  • 42
  • 207
  • 306

1 Answers1

2

Yes you can do that. just move declaration out of if statement

function someFunc(){
  if (true) return null;
  return 'Hello, world';
}

var value=null;
if (value = someFunc()) {
  alert(value);
}
else{
alert('not hello')
}

Here is fiddle link so that you can play with it - https://jsfiddle.net/mz09rca1/

ManishKumar
  • 1,476
  • 2
  • 14
  • 22