TypeError: Cannot read property "0" from undefined

IGratch picture IGratch · Sep 22, 2013 · Viewed 137.3k times · Source

I'm getting a very weird undefined error:

function login(name,pass) {
  var blob = Utilities.newBlob(pass);
  var passwordencode = Utilities.base64Encode(blob.getBytes());
  var ss = SpreadsheetApp.openById("");
  var sheet = ss.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var i=1;
  while (name != data[i][0]){
    Logger.log(data[i][0]);
    i++;
  }
  if (passwordencode == data[i][1]){
    UserProperties.setProperties({
      "name" :name,
      "pass" : passwordencode
      });
    Logger.log("You are logged in");
  }
  else if (passwordencode != data[i][1]) {
    Logger.log("You are not logged in");
    UserProperties.setProperties({
      "name" : "",
      "pass" : ""
      });
  }
}

using googlescript. The one that's undefined is the while statement where while(name != data[i][0]) claiming that you cannot read property "0" from undefined. What's weird about this, If I remove the data[i][0] in the while statement, it still works in the logger.log. And everywhere else. What the heck is going on?

EDIT: If I change the while to a if statement it also works.

Answer

Krasimir picture Krasimir · Sep 22, 2013

The while increments the i. So you get:

data[1][0]
data[2][0]
data[3][0]
...

It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.