1

I have a very simple if then statement that is not working as expected and I can't figure out why.

This is a subsection of code that I was working and have broken it down to the most basic script that is not working.

var x = 2;
if(x = 1)
  {
  Logger.log("July");
  }
  Logger.log(x);

I have hard coded x =2 and said if x =1 then log the word "July" and also logged the value of x.. after running my log shows July and 1. Both values are wrong. What am I missing?

datafarmer
  • 43
  • 1
  • 1
  • 9

2 Answers2

0

You are missing the ==. Explanation:

  • single = is used to assign a variable
  • double == is used to compare not strictly two variables
  • triple === is used to compare strictly two variables (the types are also compared)
var x = 2;
if(x == 1) {
   Logger.log("July");
}

Logger.log(x);

If you want to learn the basis of javascript (the language used in google app scripts) -- take the codecademy recommended introduction course here.

filipe
  • 1,957
  • 1
  • 10
  • 23
0

Google Apps Script is based on JavaScript.

= is used for assigning in JavaScript, so currently you're using = to define your variable var x = 2, then re-assigning x = 1 in your if statement, which is why it's returning true.

You need to use == or === in your if statement when trying to compare values. See documentation below to read up on which you should use for your purpose and why.

Reference:

  1. JavaScript Equals Operators
ross
  • 2,684
  • 2
  • 13
  • 22