Andrew C
Andrew C

Reputation: 25

Hoisting issues in declaring variables then use them within each other in Google Script?

I've declared two variables (link1 and link2) and use them within another declared variable (message). Then I created an if-statement where I use 'message' but I want to change the value of the two variables within the if-statement. In the end, I get a wrong output.

var link1, link2;
var messageFailed = "undefined";
var message = "Your first link: " + link1 + "Your second link: " + link2

if(true){
link1 = "Hello"
link2 = "World"
MailApp.sendEmail(message);
}
MailApp.sendEmail(messageFailed);

I can simply re-declare the 'message' variable within the if-statement, but I plan on using multiple if-statements so the code will end up looking really messy and a pain to change the 'message' text if needed. How would I go about changing the 'link1' and 'link2' variables after the 'message' variable is already declared?

Upvotes: 1

Views: 54

Answers (3)

basic
basic

Reputation: 3408

So as I mentioned in a comment, you cannot because it is assigned to a value. What you could do though is write a super tiny helper function to format it.

var link1 = "", link2 = "";
var message = () => {
  return "Your first link: " + link1 + " Your second link: " + link2;
}

if(true) {
    link1 = "waffles";
    link2 = "juicyfruit";
    console.log(message());
}

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817228

How would I go about changing the 'link1' and 'link2' variables after the 'message' variable is already declared?

You can change link1 and link2 but it will never affect the value of message, because you cannot go back in time. The string concatenation has already happened.

Instead you can create a function that generates the message based on the parameters it get passed:

function createMessage(link1, link2) {
  return "Your first link: " + link1 + "Your second link: " + link2
}

if(true){
  MailApp.sendEmail(createMessage("Hello", "World"));
}

That's how code reuse works. You are moving the parts that are fixed into a function and make the parts that are variable parameters of that function.

Upvotes: 1

IronSean
IronSean

Reputation: 1578

When you assign message you're calculating your result and assigning it then. Changing those variables afterwards does not change the string that was calculated when you assigned message. You need to create your message after you finish changing your variables.

Upvotes: 0

Related Questions