Let's say value argument may be string or null
function doSomething1(value) {
if (value) {
// do something
}
throw new Error("No value provided");
}
function doSomething2(value) {
if (!value) {
throw new Error("No value provided");
}
// do something
}
In that case, I want to check the value and throw an error if it's null.
Question: Is there any technical difference in terms of performance or memory usage between the functions doSomething1 and doSomething2 considering that // do something part may be small or huge? Will the order of exception throwing influence the performance at any level at all or is it 100% identical use cases?
There's absolutely no difference in terms of runtime:
In both cases, if value is null, you have one boolean check and an error throw, otherwise you have one check and the execution of the // do something block.
The difference is purely code style. I personally prefer the second one as it reduces the indent level by one on // do something, and puts error handling all in one place (whereas in the first one, you have the check at the beginning of the method and the throw at the end).