Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment with double ampersand "&&" [duplicate]

Tags:

javascript

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?

like image 859
Andy Hin Avatar asked Oct 14 '12 01:10

Andy Hin


People also ask

What does double ampersand mean?

In programming, a double ampersand is used to represent the Boolean AND operator such as in the C statement, if (x >= 100 && x >= 199). In HTML, the ampersand is used to code foreign letters and special characters such as the copyright and trademark symbols. See ampersand codes and address operator.

What does || mean in JS?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.

What does double ampersand mean in JavaScript?

JavaScript uses the double ampersand ( && ) to represent the logical AND operator. The following expression uses the && operator: let result = a && b; Code language: JavaScript (javascript) If a can be converted to true , the && operator returns the b ; otherwise, it returns the a .


1 Answers

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.

like image 84
Seth Avatar answered Oct 19 '22 07:10

Seth