Consider this function:
function myFunc(){
if(someCondition){
throw new Error("there was an error")
}
return true
}
There is a chance this function could throw an error.
Let's say you wanted to make a boolean variable that represents if the function was successful.
let success;
try {
success = myFunc()
} catch {
success = false
}
To make this cleaner, you could try something like this:
function anotherFunc(){
try {
return myFunc()
} catch {
return false
}
}
let success = anotherFunc()
But what if there was a cleaner way of doing this?
Consider the following:
let success = try? myFunc() : false
This line of code uses the try
keyword combined with a ?
to create a ternary-like try/catch block; What this like of code will do is "try" the function myFunc
and default to its return value, in this case, true
. However, if at any time myFunc
throws an error, it will instead default to the value proceeding the :
, in this case, false
.