Assignment with double ampersand "&&"

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

This is a common way to make sure your function exists before you call it.

It works like this (From developer.mozilla.com):

> expr1 && expr2 Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

In other words, Javascript does not coerce the operands to boolean values unless it has to.

4 && 5 Returns 5, not true.

In your case, if the first expression is undefined (which is convertible to false), then ctx will be false, and the second expression does not get evaluated. If the first expression is a function (which cannot be converted to false), then Javascript evaluates the second expression, and assigns it's value to the ctx variable.

Solution 2 - Javascript

It will assign the return value of canvas.getContext('2d') to ctx if canvas.getContext is actually a function.

The part on the left is just to avoid an error. It makes sure that canvas has a getContext property before trying to call getContext(). This way, the code won't call canvas.getContext() if the function doesn't exist. If it didn't check first and called when the function didn't exist, an error would be logged to the console and execution would halt.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndy HinView Question on Stackoverflow
Solution 1 - JavascriptSethView Answer on Stackoverflow
Solution 2 - JavascriptTrottView Answer on Stackoverflow