-1

I'm trying to automatically create Google docs by looking at my student scores. I have an if statement that checks the score, assigns a value and a function that prints the same. Everything seems to work, except that my if statement always returns the first value. How do I fix this?

Here is my code:

function createPdf() {
  const ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Summary');
  const lastRow = ws.getLastRow();
  const score = ws.getRange(lastRow, 3).getValue();
  const templateDoc = DriveApp.getFileById('test1');

  const newTempFile = templateDoc.makeCopy(tempFolder);

  const openDoc = DocumentApp.openById(newTempFile.getId());
  const body = openDoc.getBody();
  const paragraph = body.getParagraphs();
  body.replaceText('{percentage}', percentage);
  body.replaceText('{score}', score);
  if (50.0 < score < 120.0) {
    paragraph[13].appendText('POOR') && paragraph[17].appendText('xyz.');
  } else if (score >= 120.0) {
    paragraph[13].appendText('GOOD') && paragraph[17].appendText('abc.');
  } else {
    paragraph[13].appendText('VERY POOR') && paragraph[17].appendText('ouy.');
  }

  openDoc.saveAndClose();
}
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • 1
    `if ( (50.0 < score) && (score < 120.0) )` – Sirko Dec 25 '20 at 10:13
  • Does this answer your question? [Check if a value is within a range of numbers](https://stackoverflow.com/questions/6454198/check-if-a-value-is-within-a-range-of-numbers) or [How to check if a number is between two values?](https://stackoverflow.com/questions/14718561/how-to-check-if-a-number-is-between-two-values) – Ivar Dec 25 '20 at 10:16
  • What do you mean by "my if statement always return the first value"? Can you add sample data to your question to illustrate the exact problem? – Simon van Endern Dec 25 '20 at 10:16

2 Answers2

0

You approach is always true, bcause the first part

50.0 < score

is either true or false. For the next comparison with the boolean value

boolean < 120.0

the bolean value is converted to number 0 or 1 and this value is always smaller than 120.

To overcome this you need two comparisons with logical AND &&.

50.0 < score && score < 120.0
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-1

If we use 3 > 2 > 1 as an example.

From left to right 3 > 2 is true. true = 1 & false = 0

2 > 1 becomes 1 > 1, which is trivially false.

Hence, if 50 < score is true, then 50 < score = 1. Thereby the evaluation is equivalent to 1 < 120.0 which is always true.

Pbd
  • 1,219
  • 1
  • 15
  • 32
David
  • 1
  • 4
  • To improve the quality if your answer, you need to refer to JS coercion which is in play here. – Pbd Dec 25 '20 at 12:00