I just saw someone use this piece of code:
ctx = canvas.getContext && canvas.getContext('2d');
How does the double ampersand work in this context? Would it not just assign “true” to the ctx variable?
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.
This is a common way to make sure your function exists before you call it.
It works like this (From developer.mozilla.com):
In other words, Javascript does not coerce the operands to boolean values unless it has to.
4 && 5Returns 5, not true.In your case, if the first expression is
undefined(which is convertible to false), thenctxwill be false, and the second expression does not get evaluated. If the first expression is a function (which cannot be converted tofalse), then Javascript evaluates the second expression, and assigns it’s value to thectxvariable.