• Register
100 points
7 4

We run javascript directly in the console without the further step of compiling by yourself. But at least the javascript engine shows error. This article will discuss the error “cannot read property '0' of undefined” via example.
This error means that, somewhere in  our program we want to access property ‘0’ through our code. But the browser is unable to access the property ‘0’.
 

Example

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" : ""
      });
  }
}

Cause

As we know that this error shows up whenever our browser was unable  to access the property  ‘0’. In  the code above, in the while we are incrementing by 1 for each loop but we are not breaking the loop when we have our answer, which is in this case property ‘0’.

Solution

To resolve this issue, we just have to modify our loop a little bit and this we have to break our loop when we get our property ‘0’. The loop will look like this…

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

Hope this will help.
 

100 points
7 4