Randy
Randy

Reputation: 4525

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")

Upvotes: 11

Views: 6281

Answers (1)

XCS
XCS

Reputation: 28157

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).

Upvotes: 8

Related Questions