I know that jslint/jshint don't like it but I wanted to know if there were any real issues with doing something like.
var err = function(msg) { throw new Error(msg); };
Example 1: Assignment
var foo = bar.foo || baz.foo || err('missing foo property');
Example 2: Validation
typeof foo['bar'] !== 'string' && err('bar has to be a string');
Are there any gotcha's that I should be aware of?
In JavaScript, short-circuiting is the evaluation of an expression from left to right with || and && operators. If the condition is met and the rest of the conditions won't affect the already evaluated result, the expression will short-circuit and return that result (value).
One of the reasons often cited is lazy evaluation. Javascript has the fame of being functional, but it lacks a native way to do most of the stuff commonly considered as such. Again, one of those is lazy evaluation.
Typescript 4.0 has some cool features that can be used in Angular 11. One such feature is short-circuiting assignment operators.
Short-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.
As far as I'm aware, this is no more wrong than or die()
in PHP. The short-circuit-ness of the operator is clearly-defined, so the error will only be thrown if the last case is reached.
As covered in the comments there is a strong chance of unexpected behavior due to JavaScript's loose interpretation of truthiness which is the driving force of the mentioned logical operators. As such there is a limited subset of conditionals in which the short circuit approach will be useful, and it therefore does not offer a consistent solution.
Out of the 2 examples given example 2 is a good application as it is a readable application of a test with very defined output. Example 1 however will cause issues if any of the attempted values evaluate to anything which may be valid in the program logic, but false
from the perspective of the language. Applying a solution to these types of problems would effectively cancel out any benefit that the syntax could offer. Solutions for variations on these types of issues may not be consistent, and therefore this introduces a higher risk of bugs introduced at initial creation or any subsequent modifications.
One of important things to consider is the precedence and interaction with some other operators. Incorrectly placed ,
or brackets can change flow in subtle and not-so-easily readable way. Otherwise it should be safe as long as you ensured that you intended logic matches shortcut rules. And of course, usual gotchas to what language consider truthly apply as well.
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