Program Structure & Variables in JavaScript
Pre-Work
- Read Program Structure until you get to Conditional execution.
- Read Variables. Be sure to work through and understand the Tasks. You can use your Developer Console.
- Read Data Types. This should be mostly a review.
Introduction
- Icebreaker: What do you think a variable is in programming?
- Real-world scenario: Think of a variable as an π using its arms to bind itself to values.
- Lesson objectives: Learn about variables, their types, and how to use them in JavaScript.
- Introduction to the concept: Variables are fundamental in programming, allowing us to store and manipulate data.
Expressions and Statements
In JavaScript, a statement is a complete instruction that performs an action. For example, declaring a variable or calling a function are statements. Statements can be simple or complex, and they often end with a semicolon (;), although JavaScript can usually infer the end of a statement without it.
An expression is a sentence fragment while a statement is a complete sentence. An expression produces a value, while a statement performs an action. A statement usually does something more meaningful, like creating a variable, calling a function, or controlling the flow of the program.
5 + 3; is an expression that evaluates to 8, but const sum = 5 + 3; is a statement that declares a variable sum and assigns it the value of the expression 5 + 3. In the former, nothing is done with the value 8, it's created and then discarded or garbage collected. In the latter, the value 8 is stored in the variable sum for later use. A statement typically has consequences and repercussions in the program, while an expression simply produces a value.

Variable Bindings
A variable is a reference to a value stored in the computer's memory.
From Eloquent JavaScript's apt analogy, values float around in a sea of data, and variables are an π octopus' tentacles grasping at these values, creating variable bindings.
The analogy takes it a step further by mentioning variable names being tattooed onto these tentacles, representing variable names.
Variables declared with the keyword const (which is what we should be doing 99% of the time) cannot be reassigned. In this case, the π tentacle will forever clutch this same value, never releasing it as long as it's alive.
This π analogy is actually a much more accurate mental model than others where variables are described as boxes storing values, or similar ππΎ.
console.log()
This may not have much meaning at the moment, but we will repeat this mantra throughout the course, "Everything in JavaScript is an object, except for primitives. And even those can be treated like objects sometimes."
JavaScript has many built in objects, all of which extend from the base prototype Object. One of the most commonly used built-in objects is console, which provides access to the browser's debugging console (or the terminal console when using Node.js).
Both the browser dev console and Node.js provide this built in object called console. And, just like any other object, we use dot notation to access its properties and methods.
Properties are just values associated with the object, while methods are functions that belong to the object. Properties describe an object while methods perform actions.
In the case of the console object, we don't much care about its properties, we just want to do things with it. The most commonly used method of the console object is log(), which outputs messages to the console by accepting one or more arguments.
An argument is just a value you pass into a function whenever you call it. Here, arguments are good things. They provide the information βΉοΈ that a function/method needs to do its job. console.log() can take multiple arguments, separated by commas. Each argument can be a string, number, boolean, variable, or even an expression.
console.log("Hello, World!"); // Logs a string
console.log(42); // Logs a number
console.log(true); // Logs a boolean
const name = "Alice";
console.log("User name is:", name); // Logs a string and a variable
console.log("Sum of 5 + 3 is:", 5 + 3); // Logs a string and an expression
Note for Java/C# learners JS is an OOP language like those others, but it's more than that. It also supports functional and procedural programming styles. Those other languages have been adopting more functional features over time, but JS has always had them. Furthermore, JS uses prototypal inheritance rather than class-based inheritance, which is a key difference.
Browser Function/Methods
The readings reference alert(), prompt(), and confirm() functions that are built into web browsers. These functions create pop-up dialog boxes that interact with the user. These would only work in the browser environment, not in Node.js.
All of these functions are methods of the window object. Since JS is just a mere programming language, it doesn't know about the web browser, but it does understand objects very well. Therefore, the ever graceful web browser offers up to JS all of its functionality packaged into a single giant global object called window.
True functions, as we will learn later, are not tied to any object. They stand alone. Methods, on the other hand, are functions that belong to an object and must be accessed via . notation, with the exception of global objects such as window.
Hands-On Application
Step 1: Open the Browser Console
For these exercises, we'll use the browser's developer console - a built-in tool that lets you write and test JavaScript immediately without creating files.
"Wait, didn't we set up VS Code?" Yes! We'll use VS Code extensively in upcoming lessons. For now, we're starting with the console because:
- Immediate feedback - see results instantly without running files
- Focus on concepts - no file management distractions
- Professional skill - developers use console constantly for testing ideas
- Perfect for basics - simple variables and operations don't need file complexity
- Open your web browser (Preferably Chrome or FF Developer Edition for best experience)
- Open the developer console:
- Chrome: Press
F12orCtrl+Shift+I(Windows) /Cmd+Option+I(Mac) - Firefox: Press
F12orCtrl+Shift+K(Windows) /Cmd+Option+K(Mac)
- Chrome: Press
- Find the Console tab - click on it if it's not already selected
- You should see a prompt (usually
>) where you can type JavaScript code
Step 2: Your First JavaScript Code
-
Type this in the console and press Enter:
console.log("Hello, World!"); -
Try another line:
console.log("I'm learning JavaScript!"); -
You should see the output appear immediately in the console!
You will also see undefined after each console.log() call because the method itself does not return a value. The purpose of console.log() is to display information in the console, not to produce a value that can be used elsewhere.
This console environment will always output the result of the last expression evaluated, which is undefined for console.log(). ;)
Pro tip: You can press the β (up arrow) key to repeat previous commands.
Console Workflow Tips
For longer code blocks: Instead of typing line by line, you can:
- Use Shift+Enter to create multiple lines without executing
- Copy and paste entire code blocks at once
- Type in any text editor first, then copy to console if needed
Common console quirks:
- Variables disappear: If you refresh the page, all your variables are lost - this is normal!
- Autocomplete suggestions: Console might suggest variables from the website - just ignore these
- Red error messages: Totally normal when learning - read them for helpful clues
- Long outputs get cut off: Click the expand arrows to see more
Remember: Making mistakes is how we learn! Every programmer, including your instructor, makes typos and errors daily. The console is a safe space to experiment, break things, and try again. π§ͺ
Pro workflow: Keep your console open in a blank tab (about:blank or new tab) to avoid interference from website code. If the console becomes cumbersome, that's normal - we'll introduce file-based coding in upcoming lessons when projects get more complex!
Step 3: Working with Variables
Variables let you store and reuse information. Let's practice in the browser console!
First, let's learn about comments: Comments are notes you can add to your code to explain what it does. They start with // and JavaScript completely ignores them. Comments help you (and others) understand your code later.
// This is a comment - it explains what the code does
const age = 25; // You can also put comments at the end of a line
Comments are like sticky notes for your code - use them to remind yourself what you were thinking!
-
In the console, type each line and press Enter:
// This is a comment - it explains what the code does // Comments start with // and are ignored by JavaScript // Creating variables with const (default choice) const firstName = "Alex"; -
Continue with more variables:
const age = 25; const isStudent = true; -
Display the variables:
console.log("First Name:", firstName); console.log("Age:", age); console.log("Is Student:", isStudent); -
You should see the output appear as you type each line!
Note: You can type multiple lines at once by holding Shift and pressing Enter to go to a new line without executing.
Step 4: Variable Types Challenge
Quick Challenge: Your Personal Data
-
Create 4 variables about yourself:
const myName = "Your actual name"; const myAge = 20; // Your real age const isStudent = true; // Are you a student? const favoriteNumber = 7; // Pick any number -
Test the types:
console.log("Name type:", typeof myName); console.log("Age type:", typeof myAge); console.log("Student type:", typeof isStudent); console.log("Number type:", typeof favoriteNumber); -
Display your data:
console.log("Hi, I'm", myName, "and I'm", myAge, "years old!");
That's it! You understand data types when you can predict what typeof will return.
Step 5: Basic Operations Practice
Practice with Your Numbers
-
Math with your data:
const num1 = 10; // Use your age or any meaningful number const num2 = 5; // Use another number that matters to you const sum = num1 + num2; const product = num1 * num2; console.log(num1, "+", num2, "=", sum); console.log(num1, "*", num2, "=", product); -
Combine strings:
const firstName = "Your name"; const lastName = "Your last name"; const fullName = firstName + " " + lastName; console.log("Full name:", fullName); -
When values change (this is when we use
let):let counter = 0; console.log("Start:", counter); counter = counter + 5; console.log("After adding 5:", counter);
Template Literal Challenge: Try rewriting the string combination using backticks and ${} instead of +!
Step 6: Put It All Together
Simple About Me Program
Combine what you've learned into one small program:
// Your basic info
const name = "Your name here";
const age = 20; // Your actual age
const city = "Your city";
const isLearningJS = true;
// Display your info
console.log("=== About Me ===");
console.log("Name:", name);
console.log("Age:", age);
console.log("City:", city);
console.log("Learning JavaScript:", isLearningJS);
// One calculation
const yearsTo30 = 30 - age;
console.log("Years until 30:", yearsTo30);
Your turn:
- Replace the placeholder values with your real information
- Try rewriting one of the console.log statements using template literals
- Add one more piece of information about yourself
That's it! You've created a JavaScript program using variables, data types, and operations.
Advanced Concepts & Comparisons
let, const, and var: Variable Declaration Keywords
Important note about the pre-work readings: You'll notice the JavaScript.info article starts examples with let. This was written when const wasn't as widely adopted. In 2025, modern development practices have evolved!
Modern best practice: Use const by default, let only when you need to reassign the variable, never var.
Why const by default?
- Prevents accidental changes - catches bugs before they happen
- Communicates intent - makes it clear the value shouldn't change
- Team standards - most modern codebases and linters enforce this
- Functional programming influence - immutability is preferred when possible
Note: Different teams may have varying standards, but const-by-default is increasingly the norm at modern companies.
// Good examples
const PI = 3.14159; // Never changes
const userName = "alex2024"; // Won't change in this program
const score = 0; // Will change as game progresses
const currentLevel = 1; // Will increase over time
// This would cause an error:
// PI = 3.14; // Can't change const variables!
String Operations and Template Literals
Traditional string combination:
const name = "Sarah";
const age = 28;
const message = "Hi, I'm " + name + " and I'm " + age + " years old.";
Modern template literals (easier!):
const name = "Sarah";
const age = 28;
const message = `Hi, I'm ${name} and I'm ${age} years old.`;
Numbers and Math Operations
const a = 10;
const b = 3;
console.log("Addition:", a + b); // 13
console.log("Subtraction:", a - b); // 7
console.log("Multiplication:", a * b); // 30
console.log("Division:", a / b); // 3.333...
console.log("Remainder:", a % b); // 1
// Built-in Math functions
console.log("Square root of 16:", Math.sqrt(16)); // 4
console.log("Random number:", Math.random()); // 0.something
console.log("Round 3.7:", Math.round(3.7)); // 4
Troubleshooting & Best Practices
Common Beginner Errors
"SyntaxError: Unexpected token"
// β Wrong - missing quotes
const name = Alex;
// β
Correct - strings need quotes
const name = "Alex";
"ReferenceError: variable is not defined"
// β Wrong - typo in variable name
const firstName = "John";
console.log(firstname); // lowercase 'f'
// β
Correct - exact spelling matters
const firstName = "John";
console.log(firstName);
"Uncaught SyntaxError" in browser console
- Solution: Check your syntax - missing quotes, brackets, or semicolons
- Tip: The browser will show you the line where the error occurred
- Common fix: Make sure all strings are wrapped in quotes
JavaScript Best Practices
Naming conventions:
// β
Good variable names (camelCase)
const firstName = "John";
const userAge = 25;
const isLoggedIn = true;
const bankAccountBalance = 1500.75;
// β Avoid these naming styles
const first_name = "John"; // snake_case (Python style)
const UserAge = 25; // PascalCase (for classes only)
const x = true; // Not descriptive
const a1b2c3 = 1500.75; // Meaningless
Code organization:
// Group related variables together
const userName = "alex2024";
const userEmail = "alex@email.com";
const userAge = 22;
// Add blank lines between different sections
const gameScore = 0;
const gameLevel = 1;
const gameLives = 3;
// Use comments to explain what sections do
// === Player Statistics ===
console.log("Player:", userName);
console.log("Score:", gameScore);
Console.log() tips:
// β
Descriptive output
console.log("User name:", userName);
console.log("Current score:", gameScore);
// β Hard to understand output
console.log(userName);
console.log(gameScore);
// β
Use multiple values in one log
console.log("Game status:", gameLevel, gameScore, gameLives);
Browser Console Tips
Useful console shortcuts:
- β/β arrow keys: Navigate through command history
- Tab: Auto-complete variable names and functions
- Ctrl/Cmd + L: Clear the console screen
- Shift + Enter: Create multi-line input without executing
- Ctrl/Cmd + Shift + J: Open console directly (Chrome)
Console features:
- Variable inspection: Just type a variable name and press Enter to see its value
- Error highlighting: Syntax errors are highlighted in red
- Auto-complete: Console suggests completions as you type
- History: Your commands are saved for the session
Wrap-Up & Assessment
Key Takeaways
- JavaScript runs everywhere - browsers, servers, mobile apps
- Variables store information using
constby default,letwhen reassignment is needed - console.log() displays output - your main debugging tool
- Browser console provides immediate JavaScript execution for learning
- Strings, numbers, and booleans are the basic data types
- Good naming makes code readable - use descriptive variable names
Understanding What You've Built
Your JavaScript skills now include:
- Variable creation and manipulation using proper syntax
- Data type understanding (strings, numbers, booleans)
- Console output for debugging and displaying results
- Basic operations (math and string concatenation)
- Browser console usage for immediate JavaScript execution
- Best practices for naming and code organization
This foundation enables:
- Interactive web pages with user input and response
- Data processing and calculations in programs
- Building larger applications with multiple files and functions
- Learning advanced JavaScript concepts like functions and objects
JavaScript Quick Reference
// Variables (modern approach)
const permanent = "cannot be changed"; // Default choice
let changeable = "can be updated"; // Only when reassignment needed
// Data types
const text = "Hello"; // String
const number = 42; // Number
const decimal = 3.14; // Number
const truth = true; // Boolean
const falsy = false; // Boolean
// Output
console.log("Display this message");
console.log("Variable value:", text);
console.log(text, number, truth);
// Operations
const sum = 5 + 3; // 8
const difference = 10 - 4; // 6
const product = 6 * 7; // 42
const quotient = 15 / 3; // 5
const remainder = 17 % 5; // 2
// String concatenation
const full = "Hello" + " " + "World"; // "Hello World"
const modern = `Hello ${text}`; // Template literal
// Browser console usage
// Type commands directly and press Enter
// Use β/β keys to navigate history
Quick Assessment
Test your understanding:
-
What's the difference between
letandconst?- Answer:
constprevents reassignment (use by default),letallows reassignment (use when needed)
- Answer:
-
How do you execute JavaScript code in the browser?
- Answer: Open developer console and type code, then press Enter
-
Which is correct for storing text?
- a)
const name = Alex; - b)
const name = "Alex"; - Answer: b) - strings need quotes
- a)
HW: Hands-On Practice Screenshots
Submit screenshots of your completed exercises:
β Required Submissions:
-
Variable Types Exercise:
- Screenshot showing your 4 personal variables
- Screenshot of the
typeofresults - Screenshot of your display output
-
Operations Practice:
- Screenshot of your math calculations with your numbers
- Screenshot of your string combination
- Screenshot of your counter example
-
About Me Program:
- Screenshot of your complete "About Me" program
- Screenshot showing at least one template literal implementation
β Completion Criteria:
- Used your actual personal information (not placeholder text)
- Screenshots show working final results (errors during development are normal!)
- Demonstrated understanding of
constvslet - Applied template literals in at least one example
HW: Pre-Work Reflection
Submit as a separate Markdown (.md) file addressing these questions:
-
How did the pre-work readings help you? Did reading about program structure and variables before the hands-on practice make the concepts clearer? What connections did you make between the reading and the console exercises?
-
Building on previous knowledge: We covered values, types, and operators in the previous lesson. How did today's focus on variables and program structure build on what you already learned? What felt familiar vs. new?
-
If you're taking other programming classes: Was there anything surprising about JavaScript compared to other languages you've encountered? How does JavaScript's approach to variables and types compare to what you've seen elsewhere?
-
If this is your first programming experience: How are you feeling about programming so far? What aspects feel natural and which feel challenging? Are you starting to see how these basic building blocks (values, types, operators, variables) work together?
-
The octopus analogy: Eloquent JavaScript uses the tentacle/binding analogy for variables. Did this mental model help you understand how variables work? Do you have your own way of thinking about variables?
Note: This helps us understand your learning process and adjust future lessons accordingly.
Next Steps
With JavaScript basics mastered, you're ready to:
- Complete practice exercises and homework assignments
- Learn functions for organizing and reusing code
- Build interactive programs that respond to user input
- Explore web development with HTML, CSS, and JavaScript
Congratulations! You've written your first JavaScript programs and understand the fundamental building blocks of programming.