chapter

menu4. Variables and Data

monaco

4 Variables and Data

4.1 What Variables Are and Why They Matter

As you begin writing programs that do more than print a message or perform a single calculation, you need a way to store information—something your code can remember, reuse, and change as it runs. That’s exactly what variables are for. A variable is a named container that holds a piece of data. You can think of it like a labeled box: you put something inside, give the box a name, and later you can open it, change what’s inside, or use its contents in a calculation.

In JavaScript and Google Apps Script, variables let you keep track of values such as numbers, text, dates, or even entire lists of data. Without variables, every program would be rigid and repetitive. With them, your code becomes flexible, dynamic, and capable of responding to different situations.

A simple example looks like this:

 
let score = 10 

Here, score is the variable’s name, and 10 is the value stored inside it. Once you’ve created this variable, you can use it anywhere in your script:

 
console.log(score)

To see this example execute in Google Apps Script, do the following:

  1. Open a new Google Sheet
  2. From the menu bar, choose “Extensions” then “Apps Script”
    {width:334, alt=“Opening Apps Script Editor”}

This will open the Google Apps Script editor with a new script file named “Code.gs,” showing the following:

Notice that there is already some code here in the code GS file. What you see is the basic structure of a function. We’ll talk more about functions later but it’s the structure that allows us to group multiple lines of code to execute together. To execute code, just write (or paste) the lines between the braces as follows:

Now, your code is ready to execute. To do so, click the “Run” button.

This will execute the function and open the execution log:

There are three entries in the execution log: The first and the last just show the times that the function began and completed running. The remaining item displays the value of the variable named “count” at the time that line 3 of the function ran.

You can modify the code in the “myFunction” function to run any of the examples in this section.

Now let’s continue with our discussion of variables. Modify the code as follows:

let count = 10  
 count = 20  
 count = count + 1  
 console.log(count)

The first statement defines the variable “count” and gives it a value of 10. The second statement changes the value of the variable “count” to 20. The third statement will set a new value for the “count” variable, but to calculate the new value, it must read its current value. Before it can assign the value it must evaluate “count + 1”. At this point of the code, count holds a value of 20, so “count + 1” evaluates to 21. So the variable named “count” will take on the value 21. The final statement will print 21 into the execution log. Give it a try.

This ability to store and update information is at the heart of programming. It’s how you track progress, remember user input, process spreadsheet data, or build tools that adapt to whatever information they’re given.

Variables matter because they allow your programs to:

  • Reuse values without rewriting them
  • Respond to changing data
  • Store results from calculations or user actions
  • Organize information in a clear, meaningful way
  • Build more complex logic that depends on what’s happening in the program

In Google Apps Script, variables become especially powerful because they can hold values pulled directly from a spreadsheet—like a list of names, a column of numbers, or a single cell’s content. Once that data is in a variable, your script can analyze it, transform it, or write new results back into the sheet.

As you move through this chapter, you’ll learn how to create variables, choose good names for them, and work with different kinds of data. These skills form the foundation for everything you’ll build next, whether you’re automating a spreadsheet, generating reports, or writing full applications.

4.2 Primitive Types: Strings, Numbers, Booleans

Every programming language needs a way to represent basic kinds of information. In JavaScript—and therefore in Google Apps Script—these fundamental building blocks are called primitive types. They’re the simplest forms of data your program can work with, and they show up everywhere: in calculations, text processing, decisions, and interactions with spreadsheet values.

Understanding these types will help you write clearer code and avoid common mistakes as you begin working with real data from Google Sheets.

4.2.1 Strings: Working With Text

A string is any piece of text—words, sentences, symbols, or even empty space. Strings are written inside quotes:

let name = "Ava"
let message = "Hello, world!"
let empty = ""

Strings are useful for:

  • Labels and descriptions
  • Messages you log or display
  • Data pulled from spreadsheet cells
  • Building dynamic text (like email subjects or custom messages)

You can combine strings using the + operator:

let greeting = "Hello, " + name

In Apps Script, strings are especially common because spreadsheet data often arrives as text—even when it looks like a number.

4.2.2 Numbers: Doing Math and Calculations

Numbers in JavaScript represent both whole numbers and decimals:

let age = 30
let price = 19.99
let total = age + price

You can perform all the usual arithmetic:

let sum = 5 + 7
let product = 3 * 4
let average = (10 + 20 + 30) / 3

In Google Sheets, numbers are everywhere—totals, counts, dates, percentages—so being comfortable with numeric operations is essential. Apps Script can read numbers directly from cells and use them in calculations or write new results back into the sheet.

4.2.3 Booleans: True or False Values

A boolean represents one of two possible values:

let isActive = true
let isComplete = false

Booleans are the backbone of decision‑making in your programs. They’re used in conditions, comparisons, and logic:

let score = 85
let passed = score > 70   // passed becomes true

Whenever your script needs to choose between two paths—send an email or not, update a cell or skip it, run a calculation or stop—a boolean is involved.

4.2.4 Why Primitive Types Matter

These three types—strings, numbers, and booleans—form the foundation of almost everything you’ll do in Apps Script. They allow your programs to:

  • Store and manipulate text
  • Perform calculations
  • Make decisions
  • Interpret spreadsheet data
  • Build dynamic, flexible scripts

As you begin interacting with Google Sheets, you’ll see these types constantly. A cell might contain a string, a number, or something that becomes a boolean when you compare it. Understanding how these types behave will make your scripts more reliable and easier to reason about.

Next, we’ll explore how to work with these values inside variables and how to combine them into more complex structures.

4.3 Working With Variables in Apps Script

Now that you’ve seen the basic data types—strings, numbers, and booleans—it’s time to look more closely at how variables actually behave inside your programs. Variables are the foundation of everything you’ll do in Apps Script, especially once you start pulling information out of a spreadsheet and transforming it with code.

4.3.1 Declaring Variables With let

In modern JavaScript (and Apps Script), the most common way to create a variable is with the keyword let:

let total = 0
let name = "Jordan"
let isReady = true

When you declare a variable with let, you’re telling the computer:
“Create a container with this name, and store this value inside it.”

You can change the value later:

total = total + 5
name = "Jordan Smith"
isReady = false

This flexibility is what makes variables so powerful. They allow your program to evolve as it runs.

4.3.2 Choosing Good Variable Names

A variable name should describe what the value represents. Clear names make your code easier to read and understand—especially when you come back to it later.

Good examples:

  • totalSales
  • firstName
  • isComplete
  • rowCount

Less helpful examples:

  • x
  • data1
  • thing

Apps Script doesn’t care what you name your variables, but you will. Good names make your scripts feel organized and intentional.

4.3.3 Variables and Spreadsheet Data

In Apps Script, variables often hold values pulled directly from a Google Sheet. For example:

let sheet = SpreadsheetApp.getActiveSheet()
let cell = sheet.getRange("A1")
let value = cell.getValue()

Here:

  • sheet stores a reference to the active sheet
  • cell stores a reference to cell A1 on the active sheet
  • value stores whatever is in cell A1

The first time you run code that accesses data from the spreadsheet, the Apps Script environment will prompt you to be sure that you want to allow code to access your sheet. You can probably imagine that someone with malicious intent could try to trick someone into running code that accesses or deletes sensitive data or sends email messages to other users. Every time you run code that accesses a feature of the Apps Script environment for the first time, you will be prompted with a warning message about the service that is about to be invoked. This can be a bit annoying, but it’s there for the safety of folks who may be copying and pasting code that they don’t understand. Apps Script requires you to approve the script each time a new service is introduced.

When you run the code above for the first time, you will see a prompt similar to the following:

When you indicate that you will “review permissions”, you’ll advance to the next step in the process.

Here, you’ll need to click the gray “advanced” link on the left side of the window.

Now, click the gray “Go to Untitiled project (unsafe)” link in the bottle left of the window. This will bring up the prompt that alerts you to the fact that this code is going to access data from your sheet as follows:

When you click “Continue” you authorize this script to execute with the permissions that were listed. The Apps Script environment will not prompt you to approve those permissions again is this project. However, if you add code that requires other permissions, you’ll need to through a similar approval process.

Also, sometimes the Apps Script environment will execute the script after you approve its elevated access and sometimes it does not. If you do not see the expected output, just run the script again.

Now, let’s return to our discussion of variables.

Once the data is in a variable, you can manipulate it just like any other value:

console.log("The value in A1 is: ", value)

This is where variables start to feel practical—you’re no longer working with abstract examples, but with real information from your spreadsheet.

4.3.4 Reassigning vs. Redefining

One important detail: you can change the value of a variable declared with let, but you cannot redeclare it in the same scope.

This is allowed:

let count = 10  
count = 20 // OK

This is not:

let count = 10
let count = 20    // Not allowed

Understanding this distinction helps you avoid common errors as your scripts grow.

4.3.5 Why Variables Matters

Variables are the glue that holds your programs together. They let you:

  • Capture data from a spreadsheet
  • Store intermediate results
  • Build dynamic messages
  • Track progress through a script
  • Make decisions based on changing values

As you move forward, you’ll use variables constantly—sometimes dozens of them in a single script. Getting comfortable with how they work now will make everything else feel much more natural.

4.4 Working With Text and Numbers

As you begin writing scripts that interact with real spreadsheet data, you’ll spend a lot of time working with two fundamental types of information: text and numbers. These values show up everywhere in Google Sheets—names, labels, totals, dates, prices, IDs—and understanding how to manipulate them in JavaScript (and Apps Script) is essential for building useful tools.

Even though text and numbers behave differently, the way you work with them in JavaScript is surprisingly intuitive once you see a few examples.

4.4.1 Working With Text (Strings)

Text values—called strings—are written inside quotes:

let firstName = "Jordan"
let message = "Welcome to Apps Script!"

Strings are incredibly flexible. You can:

  • Combine them
  • Break them apart
  • Insert values into them
  • Use them to build dynamic messages or labels

For example, you can join strings using the + operator:

let greeting = "Hello, " + firstName + "!"

This approach to manipulating string data is called string concatenation.

Or build more readable text using template literals:

let greeting = `Hello, ${firstName}!`

This approach to manipulating string data is called string interpolation.

When you pull text from a spreadsheet, it arrives as a string:

let sheet = SpreadsheetApp.getActiveSheet()
let city = sheet.getRange("A2").getValue()  // likely a string

Once it’s in a variable, you can transform it however you like—capitalize it, add punctuation, or combine it with other values.

4.4.2 Working With Numbers

Numbers in JavaScript represent both whole numbers and decimals:

let price = 19.99
let quantity = 3
let total = price * quantity

You can perform all the standard arithmetic operations:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Remainder: %

Apps Script reads numeric spreadsheet values as JavaScript numbers:

let amount = sheet.getRange("B5").getValue()  // a number
let doubled = amount * 2

This makes it easy to build scripts that calculate totals, averages, or other metrics directly from your data.

4.4.3 Converting Between Text and Numbers

Sometimes you’ll get a value from a spreadsheet that looks like a number but is actually stored as text. Or you may need to turn a number into text to build a message.

JavaScript gives you simple tools for this:

Convert text to a number:

let num = Number("42") // becomes 42

Convert a number to text:

let text = String(42) // becomes "42"

Apps Script often handles these conversions automatically, but it’s helpful to know how to do it yourself when needed.

4.4.4 Example: Reading a Name and Writing a Greeting

This small script reads a user’s name from cell A1 in your spreadsheet and writes a greeting like “Hello, Jordan!” into cell B1. Go ahead and put your name into cell A1.

function writeGreeting() {
  // Get the active sheet
  let sheet = SpreadsheetApp.getActiveSheet()

  // Get a reference to cell A1
  let cellA1 = sheet.getRange("A1")

  // Read the user's name from cell A1
  let name = cellA1.getValue()

  // Build the greeting message
  let greeting = "Hello, " + name + "!"

  // Get a reference to cell B1
  let cellB1 = sheet.getRange("B1")

  // Write the greeting into cell B1
  cellB1.setValue(greeting)
}

This shows how to read from and write to a single cell on a sheet. Accessing multiple cells at once is a bit more advanced and will be covered in section XXXXXXXX.

If this if the first time you are running a script that accesses data in the worksheet, you’ll have to specifically allow it, see section 4.3.3

4.4.4.1 How it works:

  • getRange("A1").getValue() pulls the name from the sheet and stores it in the variable name.
  • The script builds a new string by combining "Hello, " with the name.
  • setValue() writes the final message into cell B1.

Try putting your own name in A1, run the script, and watch the greeting appear instantly. It’s a simple example, but it captures the essence of Apps Script: reading real data, transforming it with JavaScript, and writing meaningful results back into the spreadsheet.

4.4.5 Why This Matters

Working with text and numbers is the backbone of almost every spreadsheet automation. Whether you’re:

  • Cleaning up names
  • Formatting labels
  • Calculating totals
  • Generating reports
  • Building custom messages
  • Processing rows of mixed data

…you’ll rely on these basic operations constantly.

Mastering how to read, combine, and transform text and numbers gives you the power to turn raw spreadsheet data into something meaningful—and sets the stage for more advanced scripting in the chapters ahead.

4.5 Naming Conventions and Best Practices

As your scripts grow beyond a few lines, the names you choose for your variables start to matter a lot. Good naming makes your code easier to read, easier to debug, and easier to return to weeks or months later. In Apps Script—just like in any JavaScript environment—clear, consistent naming is one of the simplest ways to write code that feels clean and professional.

4.5.1 Use Clear, Descriptive Names

A variable name should tell you what the value represents, not how it’s used or what type it is. When you read your code later, you want the meaning to be obvious at a glance.

Good examples:

  • totalSales
  • firstName
  • isApproved
  • rowCount

Less helpful examples:

  • x
  • temp
  • data1
  • flag

Descriptive names reduce mental overhead. You don’t have to remember what x means—you can just read the name and keep going.

4.5.2 Follow JavaScript’s camelCase Style

Although other style conventions can be used in JavaScript, we will use camelCase for variable and function names. This means:

  • The first word is lowercase
  • Each following word starts with a capital letter

Examples:

let customerName = "Ava"
let totalAmount = 42
let isComplete = false

CamelCase seems to be the most commonly used naming convention across the JavaScript ecosystem, so following it helps your code feel familiar and consistent.

4.5.3 Start Names With Letters, Not Numbers

Variable names must begin with a letter, underscore, or dollar sign. They cannot start with a number:

let name1 = "Jordan" // valid  
let _count = 10 // valid  
let 1stValue = 5 // not valid

Sticking to letters for most names keeps things simple.

4.5.4 Avoid Abbreviations Unless They’re Obvious

Shortened names save a few keystrokes but cost clarity. Unless the abbreviation is universally understood, spell it out.

Prefer:

  • departmentTotal over deptTot
  • emailAddress over emlAddr

Clear code is almost always better than compact code.

4.5.5 Use Boolean Names That Read Like True/False Statements

Boolean variables should sound like conditions. This makes your code easier to read when you use them in logic.

Examples:

  • customerIsActive
  • hasPermission
  • isComplete
  • shouldSendEmail

When you read a line like:

if (customerIsActive) {

…it feels natural and self‑explanatory.

4.5.6 Keep a Consistent Style Across Your Script

Consistency is more important than perfection. If you choose a naming pattern, stick with it. For example:

  • If you use firstName, don’t switch to last_name later
  • If you name one variable totalSales, don’t name another sales_total

A consistent style makes your code feel intentional and easier to navigate.

4.5.7 Why Naming Matters in Apps Script

When you start interacting with spreadsheet data, you’ll often have variables like:

let sheet = SpreadsheetApp.getActiveSheet()  
let names = sheet.getRange("A2:A20").getValues()  
let total = sheet.getRange("B1").getValue()

Clear names help you keep track of what each value represents—especially when you’re juggling multiple ranges, rows, and calculations.

Good naming is one of the simplest habits that separates messy scripts from maintainable ones. As your projects grow, you’ll be glad you invested in clarity early on.

If you’d like, we can move on to arrays and objects next, or jump into reading and writing spreadsheet data using these naming principles.