Search code examples
javascriptgoogle-apps-scriptoperatorsstring-concatenation

Why does a variable in += operation with concatenation yield mixed results based on how it's defined?


When I declare the variable and in the next statement assign values via plus equals (+=) operator by concatenating other variables and text, I receive all data stored in my object. However, it is preceded by 'undefined'. In an effort to remove the initial undefined status of the variable, I have defined it ahead of the concatenation, however, this then breaks my plus equals operator, truncating the results.

     for (var j = 0; j < itemResponses.length; j++) {
        var itemResponse = itemResponses[j]; 
        var responseTitle = itemResponse.getItem().getTitle();
        var responseAnswer = itemResponse.getResponse();
        var responseComplete;                // Inserts undefined at start of log
     // var responseComplete = "";           // Breaks += operation
     // var responseComplete = new String(); // Breaks += operation
        responseComplete += (responseTitle + ": " + responseAnswer + "; ");
      }
      Logger.log(stringData);

Log for var responseComplete;

[16-09-15 15:38:02:256 PDT] undefinedName: Name;
Member Number: 0000;
Date: 2016-09-09 09:00;
Duration: 00:00:09;
// **** Inserts 'undefined' at head of log

Log for var responseComplete = new String();

[16-09-15 15:39:02:610 PDT] Duration: 00:00:09;
// **** Breaks += operator.

Log for var responseComplete = "";

[16-09-15 15:39:42:010 PDT] Duration: 00:00:09;
// **** Breaks the += operator.

Insight into my misunderstanding of the language is greatly appreciated.

(this project is written and executed in Google Apps Script Editor)


Solution

  • The last two scenarios are easy to explain: You are resetting responseComplete to an empty string in each loop, so += doesn't make a lot of sense since you're always concatenating to an empty string.

    responseComplete += abc

    is the same as saying

    responseComplete = responseComplete + abc

    and since responseComplete = "" in every loop, then

    responseComplete = "" + abc = abc

    The first scenario is little more tricky. Since var is evaluated at parse time and not run time, this is the same as declaring the variable outside the for loop, and since it is declared but not assigned to any value, the first time it is equal to undefined

    responseComplete = responseComplete + ABC

    responseComplete = undefinedABC

    The second loop and onward the value if responseComplete is retained.

    responseComplete = responseComplete + _nextValue

    responseComplete = undefinedABC + _nextValue = undefinedABC_nextValue