Amit Singh
Amit Singh

Reputation: 11

else statement does not return text "ID not found" google apps script

Return works if there is a match but if there is no match, the else statement doesn't work. The whole code is pasted below

function doGet(e){
 return getAirportMatch(e) ;
} 
function getAirportMatch(e) {
  
  var id = e.parameter.id;
  var regExp  ="^.*"+id+".*|\\s{1}"+id+".*$//gm";

  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ggLOdIUES107tr_r8R-EAJpbRmZSty8JdXQJfb2U2tU/edit#gid=0");
  var sheet = ss.getSheetByName("Sheet1");
  var lastRow = sheet.getLastRow();
  var lookupRangeValues = sheet.getRange(1, 1, lastRow, 1).getValues();
let a = []
  lookupRangeValues.forEach(function (row, i){
     if (row[0].match(regExp))
     {
       
      a.push(lookupRangeValues[i][0]);
       
     }
  });

  if (a)return ContentService.createTextOutput(a).setMimeType(ContentService.MimeType.TEXT)
  else return ContentService.createTextOutput("ID not found").setMimeType(ContentService.MimeType.TEXT);

Upvotes: 0

Views: 74

Answers (1)

ziganotschka
ziganotschka

Reputation: 26836

You never enter the else statement

Reason:

Even if a is empty, it is still defined and thus the condition if (a) is always fullfilled.

You can verify this easily my modifying your text output and / or implementing logs.

Sample:

function getAirportMatch(e) {
  
  ...
  let a = []
  lookupRangeValues.forEach(function (row, i){
    if (row[0].toString().match(regExp))
    {      
      a.push(lookupRangeValues[i][0]);      
    }
  });
  console.log("a: " + a);
  console.log("a.length: " + a.length);
  if (a){
  console.log("if (a)")
  return ContentService.createTextOutput("a is : " + a).setMimeType(ContentService.MimeType.TEXT)
  }
  else {
  console.log("else (a)")
  return ContentService.createTextOutput("ID not found").setMimeType(ContentService.MimeType.TEXT);
  }
}

Solution:

If the conditonal statement shall only evaluate to true for not empty a, rewrite the if condition as

if (a.length > 0)

Upvotes: 1

Related Questions