0

So I have a very simple ajax setup and it was working perfectly.

function ajax_post(){
    var hr = new XMLHttpRequest();
    var f = "foo";
    var j = "bar";
    hr.open("POST", "ajax7.php", true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var rd = hr.responseText;
        }
    }
    hr.send("f="+f+"&j="+j);
}

Then I decided to slim it down by removing all the whitespace so I ended up with

function ajax_post(){var hr = new XMLHttpRequest();var f = "foo";var j = "bar";hr.open("POST", "ajax7.php", true);hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");hr.onreadystatechange = function(){if(hr.readyState == 4 && hr.status == 200){ var rd = hr.responseText;}}hr.send("f="+f+"&j="+j)}

And it stopped working, throwing an error. SyntaxError: missing ; before statement

So, I finally fixed it by adding a comma before hr.send in the one line version and it is working again.

My question...What is the significance of that comma? It works in the "expanded" version without it. Should I actually have been putting that comma in the "expanded" version all along...?

Fred Turner
  • 139
  • 1
  • 9
  • `var foo = function(){}bar();`, `var foo = function(){},bar();` and `var foo = function(){}; bar();` are three very different programs. While adding a comma may make the program syntactically correct, it won't work as you intend. – Felix Kling Feb 20 '16 at 16:37

1 Answers1

3

What is the significance of that comma?

The comma makes the program syntactically correct.

var foo = function(){}bar();

is simply invalid because you cannot have two expression (function(){} is a function expression, bar() is a call expression) adjacent to each other without an operator. The comma is such an operator:

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

var foo = function(){},bar();

Because of the way the comma operator works, this has the same effect as directly assigning bar() to foo:

var foo = bar();

So, even if adding the comma makes your program syntactically correct, it won't produce the result you want. In your specific case this would assign the return value of hr.send() to hr.onreadystatechange, which really doesn't make any sense:

// hr.onreadystatechange = function(){}, hr.send();
// is equivalent to
hr.onreadystatechange = hr.send();

You really need to add a semicolon to get two separate statements:

var foo = function(){}; bar();

Many statements, such as the variable declaration statement, are terminated by semicolons. The addition of the semicolon after the function expression tells the parser that the variable declaration statement ends there, and that the following part (bar();) is unrelated.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143