0

Is there a way in javascript to both assign and check for undefined (or null or whatever) in one line like this:

if (let myVar = DoSomethingAndReturnValue()) {
    // DoSomethingAndReturnValue() returned a falsy value and so myVar is falsy
   return
}
// myVar is now assigned with some value we can do something with it.
Brad Mathews
  • 1,567
  • 2
  • 23
  • 45
  • yes but i dont think you can declare a new variable – Daniel A. White Jul 15 '21 at 19:25
  • 1
    https://stackoverflow.com/a/2576606/1772933 – Kinglish Jul 15 '21 at 19:25
  • you would initialize myVar before the comparison.... – Kinglish Jul 15 '21 at 19:27
  • 1
    What is the goal? You can do `let x = foo() ?? "fallback"` if you want to avoid `null` or `undefined` assignments. If you just want to exit early if the variable is falsy, then you need to declare it and then check it. It's ...1 extra line. Hardly something that will have a huge impact on your code base. – VLAZ Jul 15 '21 at 19:29

1 Answers1

1

This creates a global variable but does it.

if (!(myVar = DoSomethingAndReturnValue())) {
   console.log(2);
}
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • 1
    Wouldn't advise it. It's bad for more reasons than just the global. – VLAZ Jul 15 '21 at 19:30
  • 1
    I personally am never gonna do this, in my code. Just trying to help the OP. – Tushar Shahi Jul 15 '21 at 19:30
  • Yeah, assigning a local var first would be better than the global. Too bad can't do it all at once. It has been a couple of decades since I programmed in C and I seem to dimly remember doing this assign/compare pattern back then then. Every so often which I still could. And this does work! – Brad Mathews Jul 15 '21 at 21:10