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()?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 offoo()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').