Search code examples
javascriptgoogle-apps-scriptgoogle-apps

why does my variable value change in Logger.log


I'm not sure why this code in my Google Spreadsheet App is behaving in this way. My expected output in the logger should be "Zip value is 05044" but I get another number entirely.

function getShippingType(){
  var zip = 05044;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet,
  digitOne,
  sheetName,
  zipToOutput = [];

  Logger.log("Zip Value is " + zip);

  Logger.log(zipToOutput);
  return zipToOutput;
}

Image of unexpected result


Solution

  • JavaScript is constantly trying to "coerce" data types into the data type that it "thinks" it should be. Your Zip variable is instantiated as a number. Then you are trying to concatenate a string, and a number. You are probably getting something like this:

    Zip Value is 2596
    

    You can't convert the number to a string with zip.toString() because it just returns "2596" as a string and not "05044".

    You will need to instantiate zip with quotes around it:

    var zip = "05044";
    

    This has nothing to do with the Logger.log() method. This is how JavaScript works.

    Right now you are "hard coding" the zip. But if you retrieve a value from a spreadsheet, and think that the variable type is not what you want, you can test for the data type with typeof.

    Logger.log(typeof zip)