Search code examples
javascriptgoogle-apps-scriptor-operator

GAS OR operator makes both tests ignored


I have this function looping through all sheets, and if the sheet is not hidden, add the sheet name to the array out.

function sheetnames() {

  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  var out = new Array()
  for (var i=0 ; i<sheets.length ; i++) 
    if (sheets[i].isSheetHidden()!= true){
      out.push( [ sheets[i].getName() ] 
            )}
  Logger.log(out);
}

I would also like to test for specific sheet names, which I am able to do with

if (sheets[i].getSheetName()!= 'Sheet1'){

However when I put them together with || an OR operator, both tests are ignored.

if (sheets[i].isSheetHidden()!= true || sheets[i].getSheetName()!= 'Sheet1'){

I'm not sure if it is the way I am handling || or something else I'm not seeing.

In this example, sheet1 is visible, so would pass the first part of the test.


Solution

  • (sheets[i].isSheetHidden()!= true || sheets[i].getSheetName()!= 'Sheet1')
    

    will return true if the current sheet is not hidden or not named 'Sheet1'. Or in other words, it will only return true if the current sheet is named 'Sheet1' and is hidden. That's probably not what you want, is it? Perhaps what you're looking for is the && AND logical operator?

    Also, I'd suggest you look into formatting code, why you should use !== instead of !=, and see this question for information on using var a = []; compared to var b = new Array();