Search code examples
javascriptgoogle-apps-scriptgoogle-sheetscomparison-operatorsequality-operator

Why do I get an "Invalid assignment left-hand side" error from multiple "if" statements?


My scripting knowledge is limited to some old languages like VBA-Excel. In trying to translate a VBA-Excel script to Google Apps Script, why does the following get me an "Invalid assignment left-hand side" error? It seems like I cannot continue to conditionally replace the same variable as the Script goes along, which runs for about 1500 lines and replaces many variables many times depending upon various checked conditions. At the end the last condition states are then returned as output. It really destroys my entire conversion hopes if I cannot conditionally change variables as the script goes along:

var Elevation = activeSheet.getRange(7,2).getValue();
var Desert = activeSheet.getRange(8,2).getValue();
var Highlands_mod = 0;

if (Elevation == "High Mountains") {Highlands_mod = -20;}
if (Elevation == "Highlands" && Desert = "No") {Highlands_mod = -10;}
if (Elevation == "Highlands" && Desert = "Yes") {Highlands_mod = 10;}
if (Elevation == "High Mountains") {Elevation = "Highlands";}

I have tried all sorts of different formatting on this. The error occurs as soon as I have second set of conditions that tries to modify/replace the same variable, such as between any of the first 3 "if" statements. I'm also wondering if the first and fourth "if" statements might get resolved out of the intended order and cause errors down the line.

I'm trying to do a potentially easy conversion (I hope) without spending weeks learning a new language, so I appreciate any insights.


Solution

  • You've a single equal to where you are checking for Desert.

    Explanation:

    let x = 10; // Initializes x with a value 10

    if (x == 10) {} // This checks if the value of x is 10

    if (x === 10) {} // This checks the value and the type of x whether x is a number and it's value is equal to 10

    It should be double equal to instead of a single one:

    var Elevation = activeSheet.getRange(7,2).getValue();
    var Desert = activeSheet.getRange(8,2).getValue();
    var Highlands_mod = 0;
    
    
    if (Elevation == "High Mountains") {
      Highlands_mod = -20;
    }
    if (Elevation == "Highlands" && Desert == "No") {
      Highlands_mod = -10;
    }
    if (Elevation == "Highlands" && Desert == "Yes") {
      Highlands_mod = 10;
    }
    if (Elevation == "High Mountains") {
      Elevation = "Highlands";
    }