(myVar && foo())
what does the above code mean? what is it equivalent to?
this is an inline code i think it runs on a single line
(myVar && foo())
what does the above code mean? what is it equivalent to?
this is an inline code i think it runs on a single line
it is an expression that equates to "if myVar is not falsey, run the function foo()".
If it's used like this: var x = (myVar && foo())
, the result will be:
if myVar is not falsey, x will be set to the output of foo(). if myVar is falsey, then x will be set to the value of myVar.
The expression is making clever use of short circuiting in boolean expressions. foo() will only execute if myVar evaluates to true
.
if (myVar) {
foo();
}
is much clearer. There are probably cases where this sort of code makes sense, but style checkers (if you're interested in that sort of thing) will throw a fit over it. See http://javascript.crockford.com/code.html. It's a good practice to avoid relying on semicolon insertion and expression statements.
edit: Note that var x = a && b();
probably isn't such a bad idea in certain contexts. However, (a && b())
by itself is wrong in several ways. (semicolon insertion, expression statement, aside from being semantically cryptic)
The expression evaluates to myvar
if myvar
is falsey, and foo()
if myvar
is truthy. The following snippets are nearly identical.
var x = (myvar && foo());
if(myvar){ var x = foo(); } else { var x = myvar; }
The foo() function will only be called if myVar is not falsey: meaning it can't be false, "", 0, null, or undefined. (Any others?)
It's more typical to see an example like this:
window.console && console.log("some helpful debug info");
This is interpreted as follows...
"If the 'window' variable has a member called 'console'..."
(It's important to prefix 'console' with 'window.' because, if console is undefined, you'll get a JavaScript error instead of false.)
"... invoke the 'log' method on the 'console' object."
when && are evaluated the left hand is evaluated first i.e. myVar
, if this is true then only the right hand side is evaluated i.e. foo()
. This is because in a statement A && B if A is false then the expression A&&B will always evaluate to false.
The above statement is usually used in the following way:
var x = myVar && foo();
this can also be written as:
if myVar is truee x = foo(), else x = false