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?

2
  • 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. Commented Jul 18, 2014 at 14:32
  • thanks @ChrisCirefice, I will keep this in consideration Commented Jul 18, 2014 at 14:38

2 Answers 2

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.

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

1 Comment

thanks. I didn't know it
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.

1 Comment

thanks! never stop learning

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.