0

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!

3
  • 4
    This is not a ternary operator. Commented Jan 23, 2012 at 2:18
  • 1
    && is AND, as it is in many languages. But also, a duplicate of stackoverflow.com/q/8916679/422184 Commented Jan 23, 2012 at 2:18
  • This is ridiculously unreadable code. Who writes code like that? ಠ_ಠ Commented Jan 23, 2012 at 2:21

3 Answers 3

2

&& 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)

Sign up to request clarification or add additional context in comments.

Comments

2

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();
}

2 Comments

Thanks. can you please show me how it would look like a normal statement? What does ">=" mean? isn't that a ternary operator? under what conditions does the function get called?
The >= means "is greater than or equal to". A ternary operator is sort of a shorthand way of writing an if/else statement. In this case, function1 will get called only if mystr.length is less than the value of b.d. If mystr.length is not less than b.d then the rest of the statement after the && doesn't matter, and will therefore not be evaluated.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.