Question

I'm trying to understand how ternary operators work and I came across this example:

b.d >= mystr.length && (function1(b, a), a=0);

What does && mean? is it used like an AND operator? how does this translate to regular statement? What does the coma before a=0 mean? Thanks!

Was it helpful?

Solution

&& is the AND operator. If the left of it is true, it's evaluate the right side (and return it). The , is the comma operator. (The comma operator evaluate both its sides, left to right, and return the right side). So this code is like:

if (b.d>=mystr.lengh) {
 function1(b,a);
 a=0;
}

(Except that your code return 0)

(My native language is C, so maybe I'm wrong, but I think that in this case, javascript work like C)

OTHER TIPS

That's not a ternary.

Also, the comma inside that grouping operator basically ensures that the group will always return the value of the last expression a=0, which is 0.

That example will always evaluate to either false or 0 (which is falsy).

Edit:

For the sake of completeness, here's a ternary operator:

a > b ? functionIfTrue() : functionIfFalse();

It is logically identical to:

if ( a > b ){
    functionIfTrue();
} else {
    functionIfFalse();
}

The && operator is the logical AND operator. It evaluates the expressions from left to right and returns the first falsey value or the value of the last expression..

If it gets to the last expression, it returns its value, whatever that is.

So:

var x = (1 < 2) && ( 4 > 3) && 'fred';

sets x to "fred", whereas:

var y = (1 < 2) && 0 && 'fred';

sets y to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top