chapter

menu2. Your First Lines of Code

monaco

2 Your First Lines of Code

2.1 Writing and Running Simple Statements

Before you can build programs that make decisions or process data, you need to get comfortable with the most basic building block of all: the expression. An expression is any piece of code the computer evaluates to produce a value — a number, a piece of text, or a calculation. Think of expressions as the meaningful phrases that supply the data your code works with.

In operations, the values you care about are usually measurements, and productivity — outputs divided by inputs — is one of the most important. We’ll compute it again and again in this chapter using two small operations you’ll get to know well. The first is a university that one year taught 18,000 students with 720 faculty, then grew to 26,000 students with 800 faculty five years later. The second is Performance Apparel, a custom t-shirt shop that makes 1,000 shirts a month on $2,000 of labor, $3,000 of materials, and $1,500 of overhead. Nearly every calculation ahead comes back to one of these two, so once you know them, the numbers will speak for themselves.

Expressions are how you turn those situations into values:

  • A plain number like 18000 (the students taught) is an expression.
  • A calculation like 18000 / 720 (students per faculty member) is an expression that evaluates to 25.
  • A piece of text in quotes, like "Performance Apparel", is an expression.

Expressions represent values, but to do something with them you wrap them in statements — the full instructions that tell the computer to act.

2.1.1 From Value to Action

An expression on its own is like a thought you haven’t spoken. The calculation 18000 / 720 represents a single-factor productivity figure — students taught per faculty member — but writing it alone doesn’t tell the computer to do anything with it. To turn it into an instruction, use a statement such as console.log():

console.log(18000 / 720) // statement: display the result
                         // 18000 / 720 is just the expression

This tells the computer to print the result — 25 students per faculty member, the university’s productivity for that year. (When it grew to 32.5 five years later, that was a real gain — we’ll measure exactly how much shortly.) One instruction, one action. Tiny as it is, this captures the essence of programming: write a clear command, and the computer carries it out exactly.

2.1.2 What Makes a Statement “Simple”

A simple statement usually does one thing — display a value, assign a variable, or call a function. For example:

console.log(1000 / (2000 + 3000 + 1500))
// multi-factor productivity: shirts produced per dollar of input,
// dividing output by labor + materials + overhead

This calculates how many shirts Performance Apparel produces for every dollar of input — about 0.154 — and displays it. Or:

let studentsPerFaculty = 18000 / 720

This stores a result for later use without displaying it. Each line is a complete thought expressed in code.

2.1.3 Running Your First Statements

The easiest place to start is the browser console. Open developer tools, switch to the Console tab, and type. (The console echoes expressions back to you, so bare expressions often show a result there too.)

These first two lines are just expressions — on their own they don’t instruct the computer to do anything lasting:

18000 / 720
"Performance Apparel"

This is a true, simple statement:

console.log(32.5 / 25 - 1) // change in productivity: a 30% improvement

Now compare these two lines:

let studentsPerFaculty = 25
studentsPerFaculty

Line one is a statement — it assigns 25 to studentsPerFaculty. Line two is just an expression: the computer can see that the value is 25, but you haven’t told it what to do with that fact. Make line two a statement and the value gets used:

let studentsPerFaculty = 25
console.log(studentsPerFaculty)

Each statement runs immediately, giving instant feedback. That write-run-observe loop is one of the best ways to learn.

2.1.4 Ending Statements

You’ll often see a semicolon (;) at the end of every line in online JavaScript. Modern JavaScript usually figures out where a statement ends from the line break on its own — a feature called Automatic Semicolon Insertion — so in this book we leave them off. Two reasons: it’s one less rule to track while you’re learning the logic, and the code reads cleaner. You may later work on projects where semicolons are the norm; for now we keep things simple.

2.1.5 Why Simple Statements Matter

It’s tempting to rush to bigger programs, but simple statements are the foundation for everything else. Even a full productivity dashboard or scheduling tool is built from thousands of small, clear instructions like these. As the book goes on, you’ll combine them into functions, loops, and conditionals — but it all starts here: one line, one action, one step toward thinking like a programmer.

2.2 console.log() and Basic Output

Before you can build anything meaningful, you need a way to see what your code is doing. That’s console.log(). It’s one of the simplest tools in the language and one you’ll use constantly. It sends a message to the console — a built-in panel where JavaScript can display information. Think of it as your program’s voice: whenever you want to check a value or confirm a calculation, you log it.

console.log("Students per faculty:", 18000 / 720)

2.2.1 Why console.log() Matters

Logging looks trivial but does a lot of work: it lets you see results (numbers, text, calculations), trace problems when something isn’t working, follow the order your code runs in, and — as a beginner — watch how JavaScript behaves. It’s not an exaggeration to call it one of the most important tools you’ll use while learning.

2.2.2 Logging Different Kinds of Values

You can log almost anything:

console.log(18000)                  // numbers (students taught)
console.log("Performance Apparel")  // strings (a company name)
console.log(32.5 > 25)              // booleans (did productivity rise?)
console.log(18000 / 720)            // expressions (a productivity ratio)

Anything after // is a comment — ignored by Apps Script. Use comments to note what a line does, record your reasoning, or temporarily disable code you don’t want to run but don’t want to delete.

You can also log several values at once:

console.log("Productivity:", 18000 / 720, "students per faculty")

The console prints the label and the result together, which makes the output easy to read.

2.2.3 Using the Console in Your Browser

To try it: open your browser, right-click and choose Inspect or Developer Tools, click the Console tab, type a line such as console.log("Testing output"), and press Enter. The message appears immediately — that instant feedback is one of the best ways to build confidence.

2.2.4 Output Isn’t Just for Beginners

Even experienced developers rely on logging — it’s a quick, flexible way to understand what code is doing without elaborate tools. You’ll learn more advanced techniques later, but console.log() will always stay in your toolkit. For now, treat it as your first and most reliable way to ask your program, “What’s going on here?”

2.3 Understanding Errors and Debugging Early

Every programmer hits errors. Hitting one isn’t a sign you’re doing it wrong — it’s a sign you’re programming. An error is just the computer saying, “I tried to follow your instructions, but something didn’t make sense.” Learning to read these messages early makes you far more confident.

2.3.1 Errors Are Part of the Process

You expect to stumble over grammar when learning any new language, and a programming language is no different. You’ll misspell a name, drop a parenthesis, or use a feature wrong. Treat errors as feedback — they point straight at what needs attention. A typical message looks like:

Uncaught ReferenceError: faculty is not defined

Intimidating at first, but with practice you’ll read these like clues.

2.3.2 Types of Errors You’ll See

Most beginner errors fall into a few buckets:

  • Syntax errors — the computer can’t parse what you wrote (a missing bracket, a stray character).
  • Reference errors — you used a name that doesn’t exist or isn’t spelled the way you think (writing faculty when you defined facultyCount).
  • Type errors — you tried an operation that doesn’t make sense, like calling something that isn’t a function.
  • Logic errors — the code runs but gives the wrong answer. These are the trickiest, because nothing complains. If your multi-factor productivity formula leaves off the parentheses around the summed inputs, you’ll still get a number — just a wildly wrong one, because the computer divides by only the first input and then adds the rest.

Knowing which bucket you’re in narrows the fix.

2.3.3 Reading Error Messages

Messages feel cryptic until you know they usually tell you three things: what went wrong, where it happened (a line number), and why the computer couldn’t continue. For example:

Uncaught SyntaxError: Unexpected token '}'

This says the computer found a closing brace it didn’t expect — usually a sign something earlier is missing.

2.3.4 Debugging: Your First Toolkit

Debugging is finding and fixing problems. Early on you’ll lean on a few simple, powerful habits: use console.log() to check values and confirm your code runs where you expect; read error messages slowly, one piece at a time; check for typos, especially in names; comment out sections to isolate the problem; and test small pieces before combining them. A classic catch is the productivity formula below — both lines run, but only one is right:

console.log(1000 / 2000 + 3000 + 1500)   // 4500.5 — wrong: no parentheses
console.log(1000 / (2000 + 3000 + 1500)) // 0.154 — correct

These habits save hours.

2.3.5 Debugging Builds Understanding

Fixing errors isn’t only about making code work — it’s how you learn. Each bug you track down deepens your sense of how JavaScript behaves, until you start anticipating problems before they happen. Debugging isn’t a chore; it’s one of the most valuable skills you’ll build.

2.4 The Idea of Syntax and Structure

Every language has rules for how words fit into meaningful sentences, and programming languages are no different. Syntax is the set of rules for writing code the computer can understand. Structure is how those rules fit together into a coherent program. If syntax is the grammar, structure is the organization.

2.4.1 Why Syntax Matters

Computers are completely literal — no tone, no guessing, no filling in gaps. Forget a parenthesis or misspell a keyword and the machine stops and reports an error, because the instruction no longer fits the expected pattern. This is valid:

console.log("Productivity improved")

Remove one character and the computer no longer knows where the statement ends:

console.log("Productivity improved"

A person might overlook the missing parenthesis; the computer can’t. Syntax rules create a predictable structure both you and the machine can rely on.

2.4.2 The Building Blocks of JavaScript Syntax

As you go, you’ll meet a handful of recurring elements: keywords like let, if, function; symbols like {}, (), []; operators like +, -, ===; comments with //; values like numbers, strings, and booleans; and identifiers — the names you choose for variables and functions. Each has a role and must appear in the right place.

2.4.3 Structure: How Code Fits Together

Where syntax governs the details, structure governs the big picture — organizing code so it’s readable and logical. JavaScript uses curly braces to group related statements:

if (newProductivity > oldProductivity) {
  console.log("Productivity improved")
  console.log("Keep the new process")
}

The braces show that both console.log lines belong to the if. Without them, only the first would depend on the condition; the second would run every time, regardless of whether productivity actually rose. The braces tell the computer to treat the grouped statements as one unit — they all run, or none do. Structure also includes indentation to show hierarchy, grouping related code, meaningful names, and a logical order.

2.4.4 Syntax + Structure = Clear Communication

Programming is communication — expressing ideas in a form the computer can execute. Syntax keeps your message valid; structure keeps it understandable. A simple way to communicate clearly is to comment your code, especially the complicated parts. Explain what each section does and it’ll be far easier to follow when you return to it months later:

// Flag the change as an improvement worth keeping only when
// the new productivity beats the old productivity.
if (newProductivity > oldProductivity) {
  console.log("Productivity improved")
  console.log("Keep the new process")
}

2.5 Transitioning to Google Apps Script in Google Sheets

So far you’ve learned JavaScript in its simplest form — small statements in the console. Now it’s time to take those skills somewhere practical, where your code interacts with real operations data. For the next part of the book we’ll shift to Google Apps Script, a JavaScript-based environment that runs inside Google Workspace, anchored in Google Sheets — where most operations data already lives.

2.5.1 Why Move to Google Apps Script Now

Apps Script is the natural next step because it lets you apply your new skills to tasks that matter: computing productivity and other operations metrics, cleaning data, generating reports, and building tools that live right inside your spreadsheets. It’s ideal for beginners — nothing to install, code runs in the browser, results show up immediately in the sheet, the language is the JavaScript you’ve already learned, and you can build genuinely useful tools in just a few lines.

2.5.2 What You’ll Learn in Google Sheets

As we move into Apps Script, you’ll learn to write functions that read and modify spreadsheet data, create custom menus and buttons, automate repetitive tasks, build small applications inside Sheets, and connect a spreadsheet to other Google services. This is where programming starts to feel powerful — instead of writing code in isolation, you’ll be shaping tools that act on real operations information.

2.5.3 How This Transition Works

You’re not leaving JavaScript behind — Apps Script is JavaScript, running in a different environment with extra features. Everything so far still applies; you’re just adding new abilities, like reading spreadsheet cells. Think of it as going from practicing chords to playing your first song: the fundamentals stay the same, but now you build something meaningful. The next chapter takes you into Sheets, shows you how to open the Apps Script editor, and helps you write your first script that touches real data.