Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "x && foo()"?

I saw somewhere else said,

x && foo();

 is equal to

if(x){     foo(); } 

I tested it and they really did the same thing.
But why? What exactly is x && foo()?

like image 223
Derek 朕會功夫 Avatar asked Aug 07 '11 02:08

Derek 朕會功夫


People also ask

What is X value?

Multiplicand × Multiplier = Product. Let us take Multipler as x, Multiplicand × x = Product. Then the formula to find the value of x is. X = product / Multiplicand.

What is IXI in math?

i x i = -1, -1 x i = -i, -i x i = 1, 1 x i = i. We can also call this cycle as imaginary numbers chart as the cycle continues through the exponents. This knowledge of the exponential qualities of imaginary numbers.

What is the X variable?

An independent variable is a variable that represents a quantity that is being manipulated in an experiment. x is often the variable used to represent the independent variable in an equation.


1 Answers

Both AND and OR operators can shortcut.

So && only tries the second expression if the first is true (truth-like, more specifically). The fact that the second operation does stuff (whatever the contents of foo() does) doesn't matter because it's not executed unless that first expression evaluates to something truthy. If it is truthy, it then will be executed in order to try the second test.

Conversely, if the first expression in an || statement is true, the second doesn't get touched. This is done because the whole statement can already be evaluated, the statement will result in true regardless of the outcome of the second expression, so it will be ignored and remain unexecuted.

The cases to watch out for when using shortcuts like this, of course, are the cases with operators where defined variables still evaluate to falsy values (e.g. 0), and truthy ones (e.g. 'zero').

like image 113
Kzqai Avatar answered Sep 17 '22 17:09

Kzqai