Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of Swift's guard statement in JavaScript?

I'm starting to develop web apps but I come from the iOS world. I was wondering if there was an equivalent of Swift's guard statement in JavaScript? I love return early pattern.

For those who may not know, guard statement is a "return early if statement", here is a very basic example:

myCondition = trueOrFalse()
guard myCondition
   else {print("myCondition is false")
         return}
print("myCondition is true")
like image 648
Randy Avatar asked Apr 21 '17 09:04

Randy


1 Answers

When inside a function you can return early. No need for an actual guard, you can use an if instead.

f () {
  myCondition = trueOrFalse()

  // Make sure `myCondition` is `true`
  if (!myCondition) return console.log("myCondition is false");

  console.log("myCondition is true")
}

PS: I return the log statement just to keep it on one line. console.log simply returns undefined, so your function will return undefined. You can split that statement on multiple lines if you think it looks better that way, or want your function return type to always the same as that might help with optimization (eg: always return an integer, so instead of undefined you could return 0).

like image 112
XCS Avatar answered Oct 20 '22 17:10

XCS