Thursday, May 10, 2012

Can anyone explain this bizarre JS behavior concerning string concatenation?


I just posted this to a gist: https://gist.github.com/2228570




var out = '';

function doWhat(){
out += '<li>';
console.log(out === '<li>'); // at this point, out will equal '<li>'
return '';
}

out += doWhat();
console.log(out, out === '<li>');
// I expect out to == '<li>', but it's actually an empty string!?



This behavior is odd, does anyone have an explanation? This is a tough thing to google. It also makes no difference if you use out += or out = out + .



EDIT: @paislee made a JSFiddle that demonstrates how if doWhat is on a separate line, it behaves as expected: http://jsfiddle.net/paislee/Y4WE8/


Source: Tips4all

4 comments:

  1. It seems you're expecting doWhat to be called before the += is evaluated.

    But, the progression of the line is:

    out += doWhat(); // original line
    out = out + doWhat(); // expand `+=`
    out = '' + doWhat(); // evaluate `out`, which is currently an empty string
    out = '' + ''; // call `doWhat`, which returns another empty string
    out = ''; // result


    The out += '<li>'; inside doWhat is updating the variable, but too late to have a lasting effect.

    ReplyDelete
  2. The confusion is that you expect doWhat() to also modify out directly. Apparently, the value that you will append to is retrieved before this function is called.

    Here's the logic:


    Get the value of out ('')
    Call doWhat() and append the result to the first value ('' + '' = '')
    Assign the result to out ('')


    Mixing return values and direct modifications this way is just asking for problems, as aptly demonstrated in your example. Perhaps you should try returning <li> instead.

    ReplyDelete
  3. Imagine it like this:

    // out is undefined
    var out = '';
    // out is ''
    function doWhat(){
    out += '<li>';
    // out is '<li>';
    return '';
    }
    out = out + doWhat();
    // out += doWhat(); is the same as:
    // out = out + doWhat(); is the same as :
    // out = '' + doWhat; because the value of `out` is read when `out` is first found
    // out is ''


    And linearized:

    // out is undefined
    var out = '';
    // out is ''
    out += '<li>';
    // out is '<li>';
    out = '' + ''; // first '' is value of `out` before function is called, second is what the function returns
    // out is ''


    Solution

    var out = '';
    function doWhat(){
    out += '<li>';
    return '';
    }
    out = doWhat() + out; // Note `out` is *after* `doWhat()`


    TL;DR

    Currently, your code evaluates the same as:

    out = out + doWhat();


    This reads the value of out before doWhat() is called. To get it working how you expect it to, simply reverse the order:

    out = doWhat() + out;


    This will read the value of out after doWhat() as you expect.

    ReplyDelete
  4. As Jonathan said above, you're returning an empty string from the function, so even though you're modifying a global variable by appending '<li>' to out inside of doWhat, javascript is going to append the returned value from the function to the value of out when you made the function call.

    You can also just do:

    var out = '';

    function doWhat(){
    out += '<li>';
    return true;
    }

    doWhat();


    Is there any particular reason you need to add things to the string both inside the function and after its value is returned?

    [edit]

    Looking at the actual example you posted in the comments to this answer, it appears to me you might be trying to conditionally return an additional value to append to out from doWhat. Correct me if I'm wrong. Your code looks like this:

    var out = '', temp;

    function doWhat(){
    out += '<li>';
    }

    out += typeof (temp = doWhat()) === 'undefined' ? '' : temp;


    From this presentation, the value of temp will always be undefined because the function returns nothing that can be typed. If you are planning on having the function sometimes return a value that you then append, you can achieve what you're looking for by breaking it into two lines at the end:

    var out = '', temp;
    function doWhat(){
    out += '<li>';
    }
    temp = doWhat();
    out += typeof (temp === undefined) ? '' : temp;


    This is a little bit awkward, though, and I would probably try to move both appends inside the function.

    var out = '';
    function doWhat () {
    out += '<li>';
    if (some condition is met) { out += 'some extra string'; }
    }
    doWhat();

    ReplyDelete