0

I'm trying to make an if statement that will replace text in a google doc based on information from a google sheet. For some reason, it will always execute the first if statement, even when the condition is false. There's probably some obvious issue I'm overlooking, but I can't figure it out.

if(court = 'Emery District'){
body.replaceText('{{Court}}', 'IN THE SEVENTH JUDICIAL DISTRICT COURT IN AND FOR EMERY COUNTY, STATE OF UTAH'); 
}
if(court = 'Carbon District') {
body.replaceText('{{Court}}', 'IN THE SEVENTH JUDICIAL DISTRICT COURT IN AND FOR CARBON COUNTY, STATE OF UTAH');
} 

I'm very new to coding. I'm just trying to make a script to help with productivity.

  • I would recommend always using the JavaScript _strict_ equality operators (`===` and `!==`). See [here](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons). The creator of JavaScript referred to `==` and `!=` as the "_evil twins_" of the strict operators, probably not entirely tongue-in-cheek. – andrewJames Jun 21 '21 at 23:14

2 Answers2

0

I believe you need == instead =

if(court == 'Emery District'){
body.replaceText('{{Court}}', 'IN THE SEVENTH JUDICIAL DISTRICT COURT IN AND FOR EMERY COUNTY, STATE OF UTAH'); 
}
if(court == 'Carbon District') {
body.replaceText('{{Court}}', 'IN THE SEVENTH JUDICIAL DISTRICT COURT IN AND FOR CARBON COUNTY, STATE OF UTAH');
} 
Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23
0

If you want to compare 2 values in Apps script (JavaScript) you'll need to use ==

Here's a little rundown of the differences

  • foo = bar - now the variable foo contains bar
  • foo == bar - this is a check if the content of foo is equal to bar's content
  • foo === bar - this not only checks if the content is the same, but also the type of the variable is the same

A little more practical:

let foo = 10;
let bar = 5;
let bazz = '5';

console.log(`foo: ${foo}`);
console.log(`bar: ${bar}`);

foo = bar;

console.log(`foo is now the exact same as bar: ${foo}`);
console.log(`bar is still the same: ${bar}`);

if(bar == bazz) { 
  console.log('Because the content of bar (the number 5) and bazz (a string that contains 5) are the same this statement is true');
}

if(bar === bazz) {
  console.log('Because the content types of bar and bazz are not the same (bar being a number and bazz being a string) this statement is false')
}

if (foo === bar) {
  console.log('Because we just assigned foo the exact same value as bar, including the data type, this statement is true')
}

Now for the actual answer to the question

If the issue really only is the if statements, this should work

if(court == 'Emery District'){
body.replaceText('{{Court}}', 'IN THE SEVENTH JUDICIAL DISTRICT COURT IN AND FOR EMERY COUNTY, STATE OF UTAH'); 
}
if(court == 'Carbon District') {
body.replaceText('{{Court}}', 'IN THE SEVENTH JUDICIAL DISTRICT COURT IN AND FOR CARBON COUNTY, STATE OF UTAH');
} 
PiratePie
  • 214
  • 2
  • 7