Variables and constants in Apps Script
Variables are used to store values.
To assign a value to a variable, you need to first declare the variable and then assign a value to it.
Declaring a variable
In modern Apps Script, you can declare a variable using either let
or const
keywords, depending on whether the value needs to change later.
let firstName; // Use let for variables that will change
const API_KEY = "ABC987XYZ"; // Use const for values that should not change
Since you haven't yet assigned a value to the variable firstName
, its value will be undefined
.
Assigning a value to a variable
A value can be assigned to a variable by using the equal to (=) operator.
let firstName = "Jack"; // Declare and assign in one step
You can also declare a variable first and assign a value to it later.
let lastName;
lastName = "Lee";
For constants, you must assign a value when you declare them:
const TAX_RATE = 0.05; // Constants must be initialized when declared
The let
and const
keywords should only be used when you declare a variable. This only happens once. Once you assign a value to a variable, you can use this value by using the variable's name.
let firstName;
firstName = "Jack";
console.log(firstName); // Jack
In the above example, the statement console.log(firstName);
will output the string "Jack" because that is the value stored in the variable firstName
.
Always declare a variable before assigning a value to it
Although Apps Script will allow you to assign a value to a variable that has not yet been declared, please do not do this. This will create something called a global variable and could cause inadvertent bugs in your program.
So, do not assign a value to a variable that has not been declared. Either declare a variable and assign a value to it at the same time OR declare a variable first and then assign a value to it.
// Do not do this
firstName = "Jack"; // this will create a global variable
// This is OK - declare a variable and assign a value to it at the same time
let firstName = "Jack";
// This is also OK - declare a variable first and then assign a value to it
let firstName; // declaration first
firstName = "Jack"; // followed by assignment
Difference between let and const
The key difference between let
and const
is that variables declared with let
can be reassigned, while variables declared with const
cannot be changed after they are initialized:
let age = 25;
age = 26; // This is fine - let variables can be reassigned
const PI = 3.14159;
PI = 3.14; // This will cause an error - const variables cannot be reassigned
Assigning a new value to a variable
You can change the value that is assigned to a variable declared with let
. Just assign a new value to it using the equal to (=) operator.
let firstName;
console.log(firstName); // undefined
firstName = "Jack";
console.log(firstName); // Jack
firstName = "Ryan";
console.log(firstName); // Ryan
firstName = "Bush";
console.log(firstName); // Bush
However, you cannot reassign a value to a constant:
const TAX_RATE = 0.05;
TAX_RATE = 0.06; // This will cause an error
Block scope with let and const
Both let
and const
are block-scoped, which means they are only accessible within the block they are declared:
if (true) {
let blockScoped = "I'm only available in this block";
const ALSO_BLOCK_SCOPED = "Me too!";
}
console.log(blockScoped); // Error: blockScoped is not defined
console.log(ALSO_BLOCK_SCOPED); // Error: ALSO_BLOCK_SCOPED is not defined
Using operators with variables
You can also use operators to perform operations on variables. These operators will operate on the values contained in the variables.
const price = 10.0;
const quantity = 20;
let totalAmount = price * quantity;
console.log(totalAmount); // 200.0
The type of a variable
A variable's type will be the same as the type of the value it contains. For example, if the variable contains a string value then its type is also string. If you haven't assigned any value to a variable, its value will be undefined
.
let firstName;
console.log(typeof firstName); // undefined
firstName = "Jack";
console.log(typeof firstName); // string
Variable names
Apps Script has certain rules that govern variable names.
Variable names can only contain letters, numbers, underscores (_) or dollar signs ($).
Variable names must start with a letter, a dollar sign ($) or an underscore (_). They cannot start with a number.
Variable names cannot contain spaces.
You cannot use certain words as variable names. These words are called reserved words. For example, you cannot use
let
as a variable name. The full list of reserved words can be found here.
Best practices for naming variables and constants
There are also some best practices that you should consider following when naming variables and constants.
Pick a name that is meaningful. Someone else reading your code should be able to understand the purpose of a variable from its name. For example, the name
aaa
does not tell us anything about the type of values it might contain. The namefirstName
tells us a lot about the purpose of the variable and the values it might contain.If the name contains multiple words, either use underscores or camel casing to make it easier to read the name. It is very hard to read the name
timesheetdueby
. It is a lot easier to readtime_sheet_due_by
ortimeSheetDueBy
.Use CAPS while naming constants so it is easy for someone reading your code to differentiate variables from constants. Also, use underscores to separate multiple words in the name.
const price = 10.0;
const quantity = 20;
const TAX_RATE = 0.05; // 5% tax rate
let totalAmount = price * quantity * (1 + TAX_RATE); // order amount + tax
Variable scopes
We'll discuss variable scopes in detail later. For now, it is enough if you know the following:
Variables can either be local in scope or global in scope.
Variables declared within a function using
let
orconst
are local in scope. This means that their values can only be accessed within the function where they are declared.Variables that are declared outside of a function are global in scope. This means that their values can be accessed anywhere in your program (even within functions).
The block scope of
let
andconst
makes them more predictable and reduces bugs compared tovar
.
Reminder: don't forget to declare a variable before assigning a value to it
When you assign a value to a variable that hasn't been declared, it will become global in scope even if you didn't want that to happen. Global variables are sometimes necessary but understanding when to create one is an advanced topic and we'll discuss that in some future article.
Modern Variable Declarations: var vs let vs const
While var
has been the traditional way to declare variables in JavaScript, modern Apps Script now supports the newer let
and const
keywords. Here's why you should consider using them instead of var
:
Key Differences
Feature | var | let | const |
---|---|---|---|
Reassignment | Can be reassigned | Can be reassigned | Cannot be reassigned |
Hoisting | Hoisted (can be used before declaration) | Not hoisted | Not hoisted |
Scope | Function-scoped | Block-scoped | Block-scoped |
Redeclaration | Can be redeclared | Cannot be redeclared in same scope | Cannot be redeclared in same scope |
Why Use let and const?Better scoping: Unlike var
which is function-scoped, both let
and const
are block-scoped, meaning they exist only within the nearest set of curly braces {}
(a block).
if (true) {
var x = 10; // Exists outside the if block
let y = 20; // Only exists inside the if block
}
console.log(x); // 10
console.log(y); // ReferenceError: y is not defined
Prevents accidental reassignments:
const ensures a variable cannot be reassigned, preventing bugs in your code.
No variable hoisting surprises: Variables declared with let
and const
cannot be accessed before they are declared, avoiding confusing behavior.
console.log(a); // undefined (hoisted but not initialized)
console.log(b); // ReferenceError: Cannot access 'b' before initialization
var a = 5;
let b = 10;
Prevents redeclaration: let
and const
prevent you from accidentally declaring the same variable twice in the same scope.
When to Use Each
Better scoping: Unlike var
which is function-scoped, both let
and const
are block-scoped, meaning they exist only within the nearest set of curly braces {}
(a block).
if (true) {
var x = 10; // Exists outside the if block
let y = 20; // Only exists inside the if block
}
console.log(x); // 10
console.log(y); // ReferenceError: y is not defined
Prevents accidental reassignments: const ensures a variable cannot be reassigned, preventing bugs in your code.
No variable hoisting surprises: Variables declared with let
and const
cannot be accessed before they are declared, avoiding confusing behavior.
console.log(a); // undefined (hoisted but not initialized)
console.log(b); // ReferenceError: Cannot access 'b' before initialization
var a = 5;
let b = 10;
Prevents redeclaration: let
and const
prevent you from accidentally declaring the same variable twice in the same scope.
Use
const
by default for values that should not changeUse
let
when you need to reassign a variableAvoid using
var
in new code - it has confusing behaviors that can lead to bugs
By adopting let
and const
, your Apps Script code will be more predictable, less prone to bugs, and aligned with modern JavaScript best practices.
DISCLAIMER: This content is provided for educational purposes only. All code, templates, and information should be thoroughly reviewed and tested before use. Use at your own risk. Full Terms of Service apply.
Small Scripts, Big Impact
Join 1,500+ professionals who are supercharging their productivity with Google Sheets automation
By subscribing, you agree to our Privacy Policy and Terms of Service