Is there an equivalent of Swift's guard statement in JavaScript?
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
).