Is there any difference between the following two snippets, or any reason to use one over the other?
if (foo) {
bar();
}
foo && bar();
In the world of computer programming, "foo" and "bar" are commonly used as generic examples of the names of files, users, programs, classes, hosts, etc. Thus, you will frequently encounter them in manual (man) pages, syntax descriptions, and other computer documentation.
Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program. Foo and other words like it are formally known as metasyntactic variables.
The second form is known as short-circuit evaluation and results in exactly the same as the first form. However the first form is more readable and should be preferred for maintainability.
This type of short-cuircuit evaluation is often seen in if-statements, where the right hand is conditionally evaluated. See the example below; bar is only evaluated if foo evaluates to true.
if (foo && bar()) {
// ...
}
The version foo && bar()
is an expression, and thus has a value:
var result = foo && bar();
When using the if
version, the above might look like this:
var result;
if (foo) {
result = bar();
}
which is more verbose.
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