How to use If Else in Google Apps Script?

This post will guide you on how to use If Else statement in Google Apps Script.

Please refer to this post if you are running scripts for the first time.

Syntax

Google Apps Script uses the Javascript Language. So this is the syntax for If Else statement

if (condition) {
  //code to be executed if the condition is true
} else {
  //code to be executed if the condition is false
}

Example of Usage

In this example, we will be using the script to set the values in Column B based on the values in column A based on the following logic:

If Column A values equals to “A”, then set value in Column B to “Apple”, else set value to “Other Fruits”.

function myFunction() {
  var spreadssheet = SpreadsheetApp.getActiveSpreadsheet();
  var rows = spreadssheet.getLastRow();

  for(i =1; i <= rows; i++) 
  {
    if(spreadssheet.getRange("A"+i).getValue() == "A") 
    {
      spreadssheet.getRange("B"+i).setValue("Apple");
    }
    else
    {
      spreadssheet.getRange("B"+i).setValue("Other Fruits");
    }
  };
}

Once you run the script, you will get the following output in your spreadsheet.

We can also change the logic in the script such that:

If Column A value does not equal to “A”, then set Column B values to “Other Fruits”, else set value to “Apple”

function myFunction() {
  var spreadssheet = SpreadsheetApp.getActiveSpreadsheet();
  var rows = spreadssheet.getLastRow();

  for(i =1; i <= rows; i++)
  {
    if(spreadssheet.getRange("A"+i).getValue() != "A")
    {
      spreadssheet.getRange("B"+i).setValue("Other Fruits");
    }
    else
    {
      spreadssheet.getRange("B"+i).setValue("Apple");
    }
  };
}

This will also result in the same output.