Skip to main content

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: Tips4allCCNA FINAL EXAM

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

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex