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?

2
  • 1
    may I ask why do you want to do so ?? technically you can, but have you considered debugging challenges? Commented Apr 26, 2019 at 9:15
  • stackoverflow.com/q/2576571/10921798 Commented Apr 26, 2019 at 9:18

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.