Search code examples
javascriptlogicexpressionoperator-keywordternary

strange behavior with ternary operator


I tried to program a function, that converts javascript objects to a http-compatible string. I achieved what I intendet to do, but I don't know why it works. My final function is:

function paramify (p) {
    var n = 0, r = "";
    for (var i in p) {
        r+=(n++==0?"":"&")+i+"="+p[i];
    }
    return r;
}

The version without the ternary operator is:

function paramify (p) {
    var n=0, r="";
    for(var i in p){
        if(n++!=0){
            r+="&"
        }
        r+=i+"="+p[i]
    }
    return r;
}

Example json-object:

{"authToken":"aqsd2","username":"test","password":"1234"}

will become:

authToken=aqsd2&username=test&password=1234

(as intendet)

May somebody explain me, why this works? I didn't expect n++ to become 0 when n is already 0.


Solution

  • It's the difference between pre and post increment. It's explained in this question: ++someVariable Vs. someVariable++ in Javascript