Thomas Stevens
Thomas Stevens

Reputation: 3

Google Scripts editor || not working in IF Statement

Can anyone please tell me why the || in if statement is not working. If I take out the || it will produce the desired results of logging the cell number if its not equal.

   function ReformatSheet() {
    
      var GoFlowWHInv = SpreadsheetApp.openById("1pXWj_UOTVy_mFB5gRUPbDfzNJcAK09Z-mDyXPKUJaLE");
      var Data = GoFlowWHInv.getDataRange()
      var Values = GoFlowWHInv.getDataRange().getValues()
    
      Values[i][4]
    
      for (var i = 0; i < Values.length; i++) {
    
        if(Values[i][4] !== "Item Type" || Values[i][4] !== "Standard Product") {
    
          Logger.log(Values[i][4]);
    
        }
      }

Here is the log that I ran both before the for loop and in the for loop.

It should log the first but not the second if it has Item Type or Standard Product therefore I should only see back to back Standard Products in the log.

12:26:12 PM Notice  Execution started
12:26:13 PM Info    Item Type
12:26:13 PM Info    Item Type
12:26:13 PM Info    Kit Product
12:26:13 PM Info    Kit Product
12:26:13 PM Info    Standard Product
12:26:13 PM Info    Standard Product
12:26:13 PM Info    Kit Product

Upvotes: 0

Views: 215

Answers (1)

Tom Sharpe
Tom Sharpe

Reputation: 34265

You should be using && not ||. In this line

if(Values[i][4] !== "Item Type" && Values[i][4] !== "Standard Product")

it will always call the logger because even if the cell contains Item Type or Standard Product, the other part of the whole expression will be true and it will print to the logger.

For example, if the cell contains Item Type

Values[i][4] !== "Item Type" evaluates to false

but

Values[i][4] !== "Standard Product" evaluates to true

false || true evaluates to true so the whole if statement succeeds.

So you should use this instead:

if(Values[i][4] !== "Item Type" && Values[i][4] !== "Standard Product")

You could also invert the logic and use ||

if(!(Values[i][4] === "Item Type" || Values[i][4] === "Standard Product"))

Upvotes: 1

Related Questions