Computer Programming 1 (JavaScript) • Environment, Syntax & Types

Console Logging — I can use console.log to inspect values and trace program flow at my level.

Learn to use console.log as your go-to debugging tool for inspecting values and understanding how your code executes step by step.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

Before modern developer tools existed, programmers had very few ways to peek inside their running programs. Early software developers in the 1960s and 1970s relied on printing output to physical terminals—actual hardware consoles connected to mainframe computers. When something went wrong, they would insert print statements into their code to see variable values, much like leaving breadcrumbs along a trail so you can retrace your steps. This idea of logging—recording messages from a running program—became one of the most fundamental debugging techniques in all of software development.

JavaScript was created in 1995 by Brendan Eich at Netscape, originally as a simple scripting language for web browsers. In those early days, developers used alert() pop-up boxes to inspect values, which was clunky and interrupted the program. As browsers evolved, built-in developer tools emerged, and console.log became the standard way to send messages to a dedicated output panel without disrupting the user experience.

1960s • Print Debugging on Mainframes

Programmers insert print statements into FORTRAN and COBOL code to output variable values to physical console terminals for debugging.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript for Netscape Navigator. Developers rely on alert() dialogs to inspect values, a frustrating and disruptive approach.

2006 • Firebug Introduces the Console

The Firebug extension for Firefox introduces a dedicated console panel, popularizing console.log() as the go-to debugging method for web developers.

2008–2010 • Chrome DevTools & Node.js

Google Chrome ships with built-in developer tools including a powerful console. Node.js brings JavaScript to servers, making console.log available outside the browser.

Today • Universal Debugging Standard

Every major browser and JavaScript runtime supports the Console API. It remains the first tool most developers reach for when investigating bugs.

The core question that console.log answers is deceptively simple: What is actually happening inside my program right now? Without a way to observe values and execution order, you are essentially coding in the dark. Console logging gives you a flashlight.

SECTION 2

Core Principles & Definitions

At its core, console.log() is a built-in JavaScript function that sends whatever value you pass into it to the developer console—a special output panel in your browser or code editor. It does not change how your program runs or what the user sees; it simply reveals information to you, the developer. Understanding a few foundational principles will help you use it effectively.

1

Syntax

The basic pattern is console.log(value); where value can be any JavaScript expression—a string, number, variable, or even a complex object.
2

Multiple Arguments

You can pass multiple values separated by commas: console.log("Score:", score);. Each value is printed with a space between them, making it easy to label your output.
3

Non-Destructive

Calling console.log() never modifies your variables or program state. It is a read-only inspection tool—like looking through a window without opening it.
4

Execution Order

Log statements execute in the order they appear in your code. By placing them at strategic points, you can trace the exact path your program follows—its program flow.
5

Any Data Type

You can log strings, numbers, booleans, arrays, objects, undefined, and null. The console formats each type differently so you can identify what you're looking at.
✦

KEY TAKEAWAY

Think of console.log() like a dashboard display in a car. While the engine (your program) runs under the hood, the dashboard shows you speed, fuel level, and engine temperature without affecting how the car drives. Each console.log is like adding a new gauge—it lets you monitor what's happening inside without changing the outcome.

SECTION 3

Visual Explanation — From Code to Console

The diagram below illustrates what happens when a short JavaScript program containing several console.log calls is executed. On the left you can see the source code with line numbers. The arrows show the order in which each line runs (top to bottom), and on the right the console output panel displays the results in the same order. Notice how each log statement produces exactly one line of output, and the values printed match the current state of the variables at that moment.

Source Code1let name = "Alice";2let score = 95;3console.log(name);4console.log("Score:", score);5score = score + 5;6console.log("New:", score);7console.log(score > 90);Console Output▸Alice▸Score: 95▸New: 100▸trueHighlighted lines produce output →
Lines highlighted in cyan contain console.log calls. Each arrow connects a log statement to its output. Notice that line 5 changes score but produces no output because it has no log call, while line 6 prints the updated value of 100.

This visual makes an important point: only lines that contain console.log produce output. Line 5 modifies the variable score but remains silent in the console. If you want to know what a value is at any particular moment, you must explicitly ask by inserting a log statement. This is the key insight behind inspecting values: the console only shows what you tell it to show.

SECTION 4

How console.log Works Under the Hood

When the JavaScript engine encounters a console.log() call, a specific sequence of events occurs. Understanding this sequence helps you predict exactly what will appear in the console and when.

Step-by-Step Execution

  • 1. Evaluate the argument(s): JavaScript first evaluates whatever expression you placed inside the parentheses. If you wrote console.log(3 + 7), the engine computes 3 + 7 to get 10 before anything is printed.
  • 2. Convert to a printable form: The evaluated result is converted into a human-readable string representation. Numbers stay as digits, strings keep their text, booleans become true or false, and objects are displayed in a structured format.
  • 3. Send to the console: The formatted output is sent to the console panel, where it appears as a new line.
  • 4. Return undefined: The console.log() function itself returns undefined. It has no meaningful return value because its job is to display, not to compute.

Data Type Formatting

The console formats different data types in distinct visual styles so you can instantly identify what kind of value you are looking at. Strings typically appear in a different color from numbers, and objects can be expanded to explore their contents. This automatic formatting is one of the reasons console.log is more useful than alert(), which converts everything to a plain string.

ExpressionConsole OutputData Type
console.log("Hello")HelloString
console.log(42)42Number
console.log(true)trueBoolean
console.log(undefined)undefinedUndefined
console.log([1, 2, 3])(3) [1, 2, 3]Array (Object)
console.log({a: 1}){a: 1}Object

How console.log formats different JavaScript data types

💡

String Concatenation vs. Comma Separation

There are two common patterns for adding labels. Using a comma—console.log("x is", x)—preserves the data type of each argument. Using the + operator—console.log("x is " + x)—converts everything to a single string. The comma approach is generally preferred for debugging because it keeps objects expandable and colors intact.

SECTION 5

Tracing Program Flow with console.log

Beyond inspecting individual values, console.log is a powerful tool for understanding program flow—the order in which statements execute. When your code contains conditional branches (if/else statements) or loops, the path through your code is not always obvious. Placing log statements at the entrance of each branch lets you see which path was actually taken.

Tracing Flow Through an if/else Blocklet temp = 85;console.log("Checking temp:", temp);temp > 80 ?(decision)TRUEFALSElog("It's hot!");msg = "Turn on AC";log("It's cool.");msg = "Enjoy!";console.log("Result:", msg);
This flowchart shows how placing console.log statements before and inside each branch of an if/else block lets you trace which path the program takes. Since temp is 85 (greater than 80), the green TRUE branch executes, and the console would show: "Checking temp: 85", then "It's hot!", then "Result: Turn on AC".

Strategic Placement Tips

1

Before Decisions

Log the condition value right before an if statement so you can see what the program is evaluating: console.log("age is", age);
2

Inside Each Branch

Place a log at the top of each if and else block with a unique label like "→ entered if block" to confirm which branch ran.
3

Inside Loops

Log the loop counter on each iteration: console.log("i =", i);. This reveals how many times the loop runs and whether the counter behaves as expected.
4

After Key Operations

Log the result immediately after a calculation or assignment to verify correctness: console.log("total =", total);

SECTION 6

Worked Example — Debugging a Grade Calculator

Imagine you have written a simple grade calculator that is supposed to compute the average of three test scores and assign a letter grade. The program runs but gives an unexpected result. Let's use console.log to find and fix the bug.

Debugging a Grade Calculator with console.log

  1. 1

    Step 1 — Write the Original Code

    Here is the buggy code. We expect an average of 90, but something seems off: let s1 = 85, s2 = 90, s3 = 95; let avg = s1 + s2 + s3 / 3; console.log(avg); The console prints 206.666... instead of 90. That's clearly wrong.
    Console shows: 206.66666666666666
  2. 2

    Step 2 — Add Strategic Logs

    We add console.log calls to inspect the individual values and the sum before division: console.log("s1:", s1, "s2:", s2, "s3:", s3); console.log("sum:", s1 + s2 + s3); console.log("s3 / 3:", s3 / 3); The individual scores are correct (85, 90, 95) and their sum is 270. But s3 / 3 alone equals 31.666…, which hints at the issue.
    Console shows: s1: 85 s2: 90 s3: 95 | sum: 270 | s3 / 3: 31.666...
  3. 3

    Step 3 — Identify the Bug

    The output from Step 2 reveals the problem. JavaScript follows order of operations (PEMDAS), so division happens before addition in the expression s1 + s2 + s3 / 3. The engine computes 95 / 3 = 31.666... first, then adds 85 + 90 + 31.666… = 206.666… We need parentheses around the sum.
    Bug: missing parentheses → s1 + s2 + (s3 / 3) instead of (s1 + s2 + s3) / 3
  4. 4

    Step 4 — Fix and Verify

    We fix the code by adding parentheses and keep our log to verify: let avg = (s1 + s2 + s3) / 3; console.log("Fixed avg:", avg); The console now correctly prints 90. Once we are satisfied the code works, we can remove the extra log statements or leave them as comments for future reference.
    Console shows: Fixed avg: 90 ✓
🔍

DEBUGGING PATTERN

The process demonstrated here follows a reliable pattern: (1) notice unexpected output, (2) add console.log around the suspicious area, (3) compare expected vs. actual values, (4) fix the code, and (5) verify with another log. This is like a doctor narrowing down a diagnosis—first you check vital signs, then you test specific areas until you pinpoint the problem.

SECTION 7

console.log vs. Other Debugging Methods

While console.log is the most accessible debugging tool, it's helpful to understand how it compares to other approaches. Each method has strengths and trade-offs, and experienced developers often combine them depending on the situation.

MethodHow It WorksStrengthsLimitations
console.log()Prints values to the developer console without pausing executionSimple, quick to add, works everywhere, non-blockingCan clutter output; must be manually added and removed; no pause/inspection of live state
alert()Shows a pop-up dialog box with a stringified valueHighly visible; pauses program until dismissedDisruptive; converts all values to strings; only one value at a time; not usable in Node.js
Breakpoints (DevTools)Pause code at a specific line and inspect all variables interactivelyPowerful; inspect full program state; step through code line by lineSteeper learning curve; requires DevTools open; harder for beginners
console.table()Displays arrays/objects in a formatted table in the consoleGreat for structured data; easy to readOnly useful for arrays/objects; not all environments support it
console.error()Prints a message styled as an error (red text) with a stack traceVisually distinct; shows call stack; easy to spotDoes not actually throw an error; just visual emphasis

Comparison of JavaScript debugging methods

⚖️

WHEN TO USE WHAT

Start with console.log for quick checks—it's like using a flashlight in a dark room. When you need to investigate a more complex problem and want to pause and look around, switch to breakpoints in DevTools—that's like turning on all the lights. As you gain experience, you'll naturally develop an instinct for which tool fits the situation.

SECTION 8

Connection to Advanced Debugging Techniques

As your programs grow in complexity, the skills you build with console.log directly translate into more advanced debugging practices. Professional developers use the same underlying principle—observing program state at specific points—but with more powerful tools.

What You Learn NowWhat It Leads To
console.log(variable) to check a valueWatch expressions in DevTools that monitor variables automatically
Placing logs at decision points to trace flowSetting breakpoints and using the step debugger to walk through code
Labeling output with descriptive stringsStructured logging frameworks (e.g., Winston, Morgan) used in production
Logging inside loops to track iterationsPerformance profiling and memory analysis in DevTools
Removing logs after fixing a bugWriting automated tests that verify values for you so manual logging is rarely needed

From console.log to professional debugging

ℹ

Looking Ahead

Don't worry about mastering all these advanced tools right now. The most important skill is the mindset you develop through console logging: asking "What do I expect to happen here?" and then verifying whether your expectation matches reality. That scientific approach—form a hypothesis, test it, draw a conclusion—is the foundation of all debugging, no matter how sophisticated the tool.

SECTION 9

Practice Problems

Test your understanding of console.log with these five problems. They start with basic recall and build toward critical thinking. Try to predict the output before checking the answer.

Question 1: CONCEPTUAL

A student writes let x = 10; but never writes a console.log statement. Will the value 10 appear anywhere in the console? Explain why or why not.
Show answer
No, the value 10 will not appear in the console. JavaScript only displays output in the console when you explicitly call a function like console.log(). Simply declaring a variable stores the value in memory, but it does not produce any visible output. The console is not a window into all of your program's memory—it only shows what you ask it to show.

Question 2: BASIC CALCULATION

What will the following code print to the console? Write each line of output exactly as it would appear. let a = 5; let b = 3; console.log(a + b); console.log("a - b =", a - b); console.log(a > b);
Show answer
The console will display three lines. First, 8 (the result of 5 + 3). Second, a - b = 2 (the string label followed by the computed difference, separated by a space because we used a comma). Third, true (the boolean result of evaluating whether 5 is greater than 3). JavaScript evaluates each expression inside the parentheses before printing it.

Question 3: INTERMEDIATE

Read the code below and predict the exact console output, including the order of the lines: let count = 0; console.log("Start:", count); count = count + 1; count = count + 1; console.log("After two increments:", count); count = count * 3; console.log("After multiply:", count);
Show answer
Line 1: Start: 0 — count is still 0 at this point. Line 2: After two increments: 2 — count was incremented twice (0 → 1 → 2) before this log. Line 3: After multiply: 6 — count (2) was multiplied by 3 to get 6. This problem demonstrates how console.log always shows the current value of a variable at the exact moment the log executes, not its initial or final value.

Question 4: APPLIED

You are building a tip calculator. The code below is supposed to compute a 20% tip on a $50 meal, but it outputs "Tip: 1" instead of "Tip: 10". Add console.log statements to diagnose the bug, explain what went wrong, and propose a fix. let meal = 50; let tipRate = 20; let tip = meal * tipRate / 100; console.log("Tip:", tip); Note: Suppose the actual buggy version uses let tipRate = 2; instead of 20.
Show answer
By adding console.log("meal:", meal, "tipRate:", tipRate); before the calculation, you would see that tipRate is 2 instead of the intended 20. The bug is a simple typo in the initial assignment. The calculation 50 × 2 / 100 = 1, which explains the wrong output. The fix is to change let tipRate = 2; to let tipRate = 20;. This example shows how logging input values before a computation can quickly reveal whether the problem is in the data or in the formula.

Question 5: CRITICAL THINKING

A classmate argues: "I don't need console.log—I can just look at my code and figure out what it does." Write a short response (3–5 sentences) explaining at least two situations where reading the code alone is insufficient and console.log becomes essential. Use specific examples from what you've learned in this lesson.
Show answer
While reading code works for very short programs, there are important situations where it falls short. First, when an expression involves operator precedence (like the grade calculator example where s1 + s2 + s3 / 3 doesn't group the way you expect), the result may differ from what you assume. A quick console.log of intermediate values reveals the actual computed result instantly. Second, when programs involve user input or data from external sources, the values are unknown at write-time—you cannot "read" what a user will type. Logging lets you see the actual runtime values. Finally, as programs grow to hundreds of lines with nested conditionals, it becomes nearly impossible to mentally simulate every execution path. Strategic logging confirms which branches actually execute, saving time and preventing false assumptions.

SUMMARY

Lesson Summary

Summary

In this lesson, you learned that console.log() is a built-in JavaScript function that sends values to the developer console without affecting program behavior. Its basic syntax is console.log(value), and you can pass multiple arguments separated by commas to label your output for clarity. The function accepts any data type—strings, numbers, booleans, arrays, and objects—and displays each in a visually distinct format.

You practiced two key uses: inspecting values (verifying that variables hold the data you expect) and tracing program flow (confirming which branches and loops actually execute). The worked example demonstrated the debugging pattern: notice a problem, add logs around the suspicious code, compare expected vs. actual values, fix the bug, and verify the fix. As you advance, these console.log skills form the foundation for more powerful tools like breakpoints and watch expressions in professional developer tools.

Varsity Tutors • Computer Programming 1 (JavaScript) • Console Logging