MRuba
MRuba

Reputation: 3

My variables reset after changing them in a for loop on the spreadsheet script section

I'm new to javascript, but have some experience with C#. So I wanted to write a script to help me count how many products of one type were sold, and how many of those were sold by a certain company. The goal was to add one to the variable numberSoldByCompany for every row that had the same value as the parameter market companyObjective. Same goes for variable numberOfProductStock and parameter marketObjective. Problem is that after I exit each for loop, these variables reset to 0. Any Ideas?

function MarketShare(marketObjective, companyObjective) {

  var numberSoldByCompany = 0;
  var numberOfProductStock = 0;

  var range = SpreadsheetApp.getActiveSheet().getRange('A110:B244');

  var rangeRows = 134;
  var rangeColumn = 2;

  for (var i = 1; i <= rangeRows; i++){
    var currentValue = range.getCell(i,1).getValue();
    if(currentValue == marketObjective){

      numberOfProductStock++;

    }
  }

  for (var i = 1; i <= rangeRows; i++){
    var currentValue = range.getCell(i,2).getValue();
    if(currentValue == companyObjective){

      numberSoldByCompany++;

    }
  }

  if (numberSoldByCompany === 0){
    return 0;
  }
  else{
    return numberSoldByCompany/numberOfProductStock*100; //returns 0/0*100
  }

}

Upvotes: 0

Views: 342

Answers (1)

Evgenii Klepilin
Evgenii Klepilin

Reputation: 695

Make sure to not confuse assignment operator = with equality operator == or strict equality ===operator. The latter not only compares values, but also types. For example, while 0 == '0' is true, 0 === '0' would be false.

...    
for (var i = 1; i <= rangeRows; i++){
    var currentValue = range.getCell(i,1).getValue();
    if(currentValue == marketObjective){ 
    // if you wanted to use strict equality here,
    // you need to fist make sure that supplied 
    // values from the spreadsheet are the same type as marketObjective

      numberOfProductStock++;

    }
  }

  for (var i = 1; i <= rangeRows; i++){
    var currentValue = range.getCell(j,2).getValue();
    if(currentValue == companyObjective){

      numberSoldByCompany++;

    }
  }

  if (numberSoldByCompany === 0){
    return 0;
  }
  else{
    return numberSoldByCompany/numberOfProductStock*100;
  }
...

Upvotes: 2

Related Questions