Am I allowed to throw an error inside a ternary operator? Is this valid:
function foo(params) { var msg = (params.msg) ? params.msg : (throw "error"); // do stuff if everything inside `params` is defined }
What I'm trying to do is make sure all of the parameters needed, which are in a param
object, are defined and throw an error if any one is not defined.
If this is just foolish, is there a better approach to doing this?
throw new Error('something went wrong') — will create an instance of an Error in JavaScript and stop the execution of your script, unless you do something with the Error.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
However, JavaScript allows you to construct nested ternary operators to replace if…else…else if statements. To an expression like this using the nested ternary operator: console.
create(Error. prototype); With a custom exception object created, all we have to do is throw it like any other error: throw new CustomException('Exception message');
You could do this:
function foo(params) { var msg = (params.msg) ? params.msg : (function(){throw "error"}()); // do stuff if everything inside `params` is defined }
I wouldn't really recommend it though, it makes for unreadable code.
This would also work (not that it's really much better):
function foo(params) { var msg = params.msg || (function(){throw "error"}()); // do stuff if everything inside `params` is defined }
Or for a cleaner approach, make a named function.
function _throw(m) { throw m; }
function foo(params) { var msg = params.msg || _throw("error"); // do stuff if everything inside `params` is defined }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With