Basic · B2
JavaScript basics
Apps Script is JavaScript. Before you control Google apps, you need the core of the language: storing values, working with them, making decisions and packing code into functions. Run every example in the editor and compare the log.
Variables are named boxes
A variable gives a value a name, so you can use it later. Modern JavaScript has two keywords:
constfor a value that will not be reassigned. Use it by default.letfor a value you will change, such as a running total.
function variables() {
const school = 'Suankularb Thonburi'; // const: will not change
let score = 70; // let: can change
score = score + 5;
console.log(school);
console.log(score);
console.log(typeof school, typeof score);
} Execution log
Suankularb Thonburi 75 string number
Old tutorials (and some code in the wild) use var. It still works, but it has confusing scope
rules. Read it, but write const and let.
Naming rules
- Use camelCase:
studentName,lastRow,totalScore. - Names are case-sensitive:
scoreandScoreare different. - Comments start with
//for one line, or go between/*and*/.
The kinds of value
| Type | Example | In a sheet this is… |
|---|---|---|
| string | 'Ploy', "M.5", `hi` | Any text cell |
| number | 82.5, -3, 0 | A number cell (also percentages and money) |
| boolean | true, false | A ticked or unticked checkbox |
| Date | new Date() | A date or time cell |
| null / undefined | null | Never: an empty cell comes back as '', an empty string |
function dataTypes() {
const name = 'Ploy'; // string
const mark = 82.5; // number
const passed = true; // boolean
const nothing = null; // null: "no value on purpose"
let notSet; // undefined: "never given a value"
const today = new Date(); // a Date object
console.log(typeof name, typeof mark, typeof passed);
console.log(nothing, notSet);
console.log(today.getFullYear());
} Execution log
string number boolean null undefined 2026
typeof tells you the type of a value. It is the first thing to check when a sheet gives you something you didn't expect.
Doing things with values
function operators() {
console.log(7 + 3, 7 - 3, 7 * 3, 7 / 2); // 10 4 21 3.5
console.log(7 % 3); // remainder: 1
console.log(2 ** 5); // power: 32
console.log('7' + 3); // joins text: 73
console.log(Number('7') + 3); // converts first: 10
console.log(5 === 5, 5 === '5'); // true false
console.log(5 > 3 && 2 > 9); // and: false
console.log(5 > 3 || 2 > 9); // or: true
} Execution log
10 4 21 3.5 1 32 73 10 true false false true
| Operator | Meaning |
|---|---|
+ - * / | Add, subtract, multiply, divide |
% | Remainder after dividing. n % 2 === 0 means n is even. |
** | Power |
=== !== | Equal / not equal, without converting types. Always use these. |
< > <= >= | Comparisons |
&& || ! | And, or, not |
+= -= ++ | Shortcuts: total += 5 is total = total + 5 |
Template literals
Joining text with + gets messy. Backticks let you put values straight into text with $${…}:
function templates() {
const name = 'Ploy';
const mark = 82;
console.log('Hello ' + name + ', you scored ' + mark + '%');
console.log(`Hello ${name}, you scored ${mark}%`);
console.log(`Next year you will be ${15 + 1}`);
} Execution log
Hello Ploy, you scored 82% Hello Ploy, you scored 82% Next year you will be 16
You will use backticks for every email body, message and file name you build in this course.
if, else if, else
Code checks conditions from the top and runs the first block that is true, then skips the rest.
function grade() {
const mark = 68;
let result;
if (mark >= 80) {
result = 'A';
} else if (mark >= 70) {
result = 'B';
} else if (mark >= 60) {
result = 'C';
} else {
result = 'Try again';
}
console.log(`Mark ${mark} → ${result}`);
} Execution log
Mark 68 → C
Change mark to 85, 70, 59 and run each time. Predict the answer first.
The short form
For a simple either/or, the ternary operator fits on one line: condition ? valueIfTrue : valueIfFalse.
const status = mark >= 50 ? 'Pass' : 'Fail';
= is not ===
if (mark = 80) sets mark to 80 and is always true. To compare, write
if (mark === 80). This is one of the most common beginner bugs.
Functions take inputs and return an output
A function can take parameters (inputs in the brackets) and return a result. Then you can reuse it anywhere. One function, many uses.
// A function with parameters and a return value.
function addVat(price, rate) {
return price + price * rate;
}
// An arrow function does the same job in one line.
const half = (n) => n / 2;
function testFunctions() {
const total = addVat(100, 0.07);
console.log(total); // 107
console.log(half(total)); // 53.5
console.log(addVat(250, 0)); // 250
} Execution log (run testFunctions)
107 53.5 250
addVathas two parameters. When you calladdVat(100, 0.07),priceis 100 andrateis 0.07.returnsends the answer back and ends the function.halfis an arrow function, a shorter way to write a small function. You will see these a lot inside loops.
Why can't I just press Run on addVat?
You can, but the editor calls it with no inputs, so price and rate are
undefined and the result is NaN ("not a number"). Write a small test function, like
testFunctions, that calls your function with real values. Run the test.
Practice
1. BMI calculator Easy
Write bmi(weightKg, heightM) that returns weight ÷ height². Test it with 52 kg and 1.6 m and print it to one decimal place (hint: .toFixed(1)).
Show a solution
function bmi(weightKg, heightM) {
return weightKg / (heightM * heightM);
}
function testBmi() {
const value = bmi(52, 1.6);
console.log(`BMI is ${value.toFixed(1)}`); // BMI is 20.3
} 2. Even or odd Easy
Write evenOrOdd(n) that returns the text 'even' or 'odd'. Use % and the ternary operator.
Show a solution
function evenOrOdd(n) {
return n % 2 === 0 ? 'even' : 'odd';
}
function testEvenOdd() {
console.log(evenOrOdd(4)); // even
console.log(evenOrOdd(7)); // odd
} 3. Weather advice Medium
Write weatherAdvice(celsius): 35 or more "Very hot", 28 or more "Hot", 20 or more "Nice day", otherwise "Bring a jacket". Test four temperatures.
Show a solution
function weatherAdvice(celsius) {
if (celsius >= 35) return 'Very hot: stay inside and drink water';
if (celsius >= 28) return 'Hot: wear a hat';
if (celsius >= 20) return 'Nice day';
return 'Bring a jacket';
}
function testWeather() {
console.log(weatherAdvice(38));
console.log(weatherAdvice(30));
console.log(weatherAdvice(24));
console.log(weatherAdvice(15));
} 4. Shop discount Medium
A shirt costs 120 baht with 10% off. Write fixMe so it prints You pay 108 baht using a template literal.
Show a solution
function fixMe() {
const price = 120;
const discount = 0.1;
const toPay = price - price * discount;
console.log(`You pay ${toPay} baht`); // You pay 108 baht
}