Skip to content
Advertisement

Setting a variable in Google Scripts based on another variable

I am new to Javascript and slowing using Apps Scripts by google to practise, firstly, how do assign the value of a global variable to another one depending on if statements. Every test of the code below gives me the last value.

JavaScript

Is there a way to simplify this? I am using the on Submit form trigger.

Advertisement

Answer

Issue:

The issue in your code is that you are not breaking when the first if condition holds true.

For example:

JavaScript

If the first case statement is true and the first if statement as well, the value of totalprice will be equal to oneweek. The issue is that you forget to break. Therefore the next case block will be automatically true, and therefore totalprice will become onefort (assuming again that day_options="Full Day").

That explains why you are getting the last value everytime.

The quick fix in your code is to put the break statement after the if blocks for every case statement.

Solution:

JavaScript

If you are looking to improve your code, this is not the right platform to request this. Instead I would advice you to post a question in the code review.

However, if you are looking to shorten your code, you can use ternary operators.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement