3


I've searched in SO but I didn't find something similar. Maybe I am using wrong search keys.
I was editing a javascript library when I found this if statment

    var a = location.hash.replace(/^#/, "");

    if (container = $("#content"), a) {
       ..content
    } else {
        ...other code
    }

the first part container = $("#content") is assigning the value of $("#content") to container but I don't understand why there is a comma inside the If. Is it like an AND operator? Something like if (container = $("#content") && a) ? What is it evaluating?

faby
  • 7,394
  • 3
  • 27
  • 44
  • 2
    Javascript is (so far) my main programming language. I've seen that operator before, but only when it's *actually* useful. In this case, it seems like that just wanted to 'save a line' by throwing the assignment in the `if` statement. In my opinion, that's not very readable. Though I suppose that if this is library code that 'every byte counts', but even then the library can/should be minified. So why they wrote the code this way... definitely a mystery to me. – Chris Cirefice Jul 18 '14 at 14:32
  • thanks @ChrisCirefice, I will keep this in consideration – faby Jul 18 '14 at 14:38

2 Answers2

4

The comma operator in JavaScript is pretty similar to the concept in other C-like languages. It's a way of stringing multiple expressions together into one (syntactic) expression. The value of the whole thing is the value of the last expression in the list.

Thus in this case, container = $("#content") is evaluated, and then a is evaluated. The value of the whole thing is the value of a.

A good question is why that code was written that way. There are times when the comma operator is useful, but usually it's just a way to save some typing and make code a little more concise.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

It is comma operator.

Basically its doing two things. First there is assignment and then the , just evaluates a and validates against it in the if condition.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95