Skip to content Skip to sidebar Skip to footer

Using Return As One Of Multiple Statements In Ternary Expression

I have this code: err ? (reject(err), return) : resolve(db) Which returns: SyntaxError: Unexpected token return However this works: err ? (reject(err), console.log('te

Solution 1:

It's a ternary expression, the expression as a whole must evaluate to a value, and thus contain only expressions.

You can't say a = 1 + return; either.

Is there other alternative to stop function execution while using ternary operator for multiple statements?

The if statement...

if (err) { reject(err); return }

resolve(db);

Solution 2:

err ? (reject(err), return)
    : resolve(db)

Is there other alternative to stop function execution while using ternary operator for multiple statements?

Ternary operators are not like if else in the sense of including an implicit return statement. So in order to return asap once the condition satisfies, you might properly do as follows.

return err ? reject(err)
           : resolve(db);

Post a Comment for "Using Return As One Of Multiple Statements In Ternary Expression"