Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "if (foo) bar();" and "foo && bar();" [duplicate]

Tags:

javascript

Is there any difference between the following two snippets, or any reason to use one over the other?

if (foo) {
    bar();
}

 

foo && bar();
like image 462
Phil K Avatar asked Jul 28 '13 12:07

Phil K


People also ask

What do FOO and bar mean?

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.

What does FOO mean js?

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.


2 Answers

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()) {
    // ...
}
like image 190
Bouke Avatar answered Sep 30 '22 17:09

Bouke


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.

like image 31
user123444555621 Avatar answered Sep 30 '22 16:09

user123444555621