blog / guides

JavaScript console.log() examples you can try yourself

by Luke published 8 min read

the short answer

console.log() is at its most useful when the output is easy to read. toFixed and toLocaleString tidy numbers, padStart and padEnd line up columns, JSON.stringify with an indent lays out objects, typeof shows what kind of value you really have, and a log inside a loop traces a bug one step at a time. The ten examples below show each one with code you can run.

console.log() shows whatever you give it, but a few small habits make that output far easier to read. This page is a set of ten examples to run and borrow, from tidying money and dates to laying out objects and chasing down a bug in a loop.

If you are new to it, start with our guide to JavaScript console.log(), which covers where the console is, logging several values and the other console methods. The examples here build on that. Every one runs in your browser: press run and the output appears underneath.

1. Money with two decimal places

try it · javascript
const price = 0.1 + 0.2;
console.log(price);
console.log(price.toFixed(2));
console.log(`Total: £${(3 * 4.5).toFixed(2)}`);
0.30000000000000004
0.30
Total: £13.50

Computers store most decimals as tiny approximations, which is why the first line looks odd. toFixed(2) rounds to two places for display. It returns text, so do your maths first and call it last.

2. Big numbers and currency

try it · javascript
const visitors = 1234567;
console.log(visitors.toLocaleString("en-GB"));
const money = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" });
console.log(money.format(1234.5));
1,234,567
£1,234.50

toLocaleString adds thousands separators in the style of a country, and Intl.NumberFormat does the full job for currency, symbol and pence included. Change "en-GB" to "de-DE" and the commas become full stops, as German readers expect. Leave the brackets empty, as in toLocaleString(), and the browser uses the visitor’s own settings, which is usually what you want on a real website but makes test output differ from one computer to the next.

3. Dates that read properly

try it · javascript
const quiz = new Date(2026, 10, 13);
console.log(quiz.toDateString());
console.log(quiz.toLocaleDateString("en-GB"));
console.log(quiz.getMonth());
Fri Nov 13 2026
13/11/2026
10

Months count from 0, so 10 means November. It is one of the most common surprises in JavaScript, and logging getMonth() is a quick way to catch it.

4. Lined-up columns

try it · javascript
const items = [["Tea", 2.5], ["Toastie", 5.25], ["Flapjack", 2.75]];
for (const [name, cost] of items) {
  console.log(name.padEnd(10, ".") + cost.toFixed(2).padStart(6));
}
console.log("=".repeat(16));
Tea.......  2.50
Toastie...  5.25
Flapjack..  2.75
================

padEnd(10, ".") adds dots after the name until it is 10 characters long, and padStart(6) adds spaces before the price until it is 6 characters, so a price of £10 or more would still line up. repeat makes a divider of any length.

5. Objects you can read

try it · javascript
const user = { name: "Sam", level: 3, badges: ["first-line", "loops"] };
console.log(user);
console.log(JSON.stringify(user, null, 2));
{"name":"Sam","level":3,"badges":["first-line","loops"]}
{
  "name": "Sam",
  "level": 3,
  "badges": [
    "first-line",
    "loops"
  ]
}

The run boxes show objects as one line of text. A browser’s console shows them as a tree you can open with a click. Either way, JSON.stringify with an indent of 2 gives a layout you can read top to bottom, which helps with bigger objects.

6. What type is it?

try it · javascript
console.log(typeof "5", typeof 5);
console.log(typeof true, typeof undefined);
console.log(typeof [], Array.isArray([]));
console.log(typeof null);
string number
boolean undefined
object true
object

When "5" + 1 gives 51, typeof tells you why: one of them was text. Two results are worth remembering. Arrays count as objects, so use Array.isArray to check for one. typeof null says object too, a mistake in JavaScript that can never be fixed without breaking old websites.

7. Tracing a loop bug

This loop should average three scores, but it prints NaN, meaning not a number. A log inside the loop shows why:

try it · javascript
const scores = [8, 6, 10];
let total = 0;
for (let i = 0; i <= scores.length; i++) {
  console.log(i, scores[i]);
  total += scores[i];
}
console.log(total / scores.length);
0 8
1 6
2 10
3 undefined
NaN

The loop runs one time too many. There is no score at position 3, so it adds undefined, which turns the total into NaN. Changing <= to < fixes it, and the average becomes 8.

8. A function that forgot to return

try it · javascript
function addVat(price) {
  const total = price * 1.2;
  console.log("inside:", total);
}
const result = addVat(50);
console.log("outside:", result);
inside: 60
outside: undefined

The function works out the right answer but never hands it back, so the caller gets undefined. Logging both inside and outside shows exactly where the value is lost. Add return total; as the last line of the function to fix it.

9. A switch for debug messages

try it · javascript
const DEBUG = true;
function debug(...parts) {
  if (DEBUG) {
    console.log("[debug]", ...parts);
  }
}
debug("basket size", 3);
debug("discount", 0.1);
console.log("Checkout ready");
[debug] basket size 3
[debug] discount 0.1
Checkout ready

Set DEBUG to false and every debug line goes quiet, while normal output stays. It saves deleting and retyping logs while you work on a tricky part of a program. ...parts collects any number of values, and the second ... passes them on to console.log.

10. Warnings and errors

try it · javascript
function setAge(age) {
  if (age < 0) {
    console.error("Age cannot be negative:", age);
    return;
  }
  if (age > 120) {
    console.warn("That age looks unusual:", age);
  }
  console.log("Age saved:", age);
}
setAge(-3);
setAge(130);
setAge(30);
Age cannot be negative: -3
That age looks unusual: 130
Age saved: 130
Age saved: 30

In a browser console, errors appear in red and warnings in yellow, and you can filter to show only those. The run boxes print all of them in the same way. Note that the warning does not stop the function, so 130 is still saved, while return after the error stops it early.

A routine for debugging with logs

The examples above each show one trick. When a real program misbehaves, the tricks work best as a routine:

  1. Log the inputs. Check that the values coming in are what you think, with typeof if there is any doubt.
  2. Log at the halfway point. If the value is right there, the bug is later. If not, it is earlier. Keep halving until you find the line.
  3. Label every log. console.log("after discount", total) beats a bare number when five logs are printing at once.
  4. Change one thing, then run again. Several changes at once make it hard to tell which one helped.
  5. Tidy up. Remove the logs once the bug is fixed, or switch them off with a debug flag like the one in example 9.

This works in any language. The guide to Python’s print examples linked below uses exactly the same approach with print.

Common mistakes

Joining an object with +

try it · javascript
const user = { name: "Sam" };
console.log("User: " + user);
console.log("User:", user);
User: [object Object]
User: {"name":"Sam"}

+ turns the object into the placeholder text [object Object]. A comma passes it as a separate value, so it keeps its contents.

Forgetting the brackets on a method

console.log(price.toFixed) logs the method itself, not a result. Methods need brackets to run, as in price.toFixed(2).

Doing maths on toFixed

toFixed returns text, so price.toFixed(2) + 1 joins a 1 on the end instead of adding. Round at the very end, once the sums are done.

Leaving debug logs behind

Logs added to hunt a bug should come out once it is fixed. Search your code for console.log before you share it.

A short exercise

Log a receipt for these three items, with names padded to 12 characters with dots and prices to two decimal places, then a divider and the total:

const basket = [["Bread", 1.35], ["Milk", 0.95], ["Apples", 2.1]];

Try it in the playground from the button at the bottom of the page, choosing JavaScript.

One possible answer

try it · javascript
const basket = [["Bread", 1.35], ["Milk", 0.95], ["Apples", 2.1]];
let total = 0;
for (const [name, cost] of basket) {
  console.log(name.padEnd(12, ".") + cost.toFixed(2));
  total += cost;
}
console.log("-".repeat(16));
console.log("Total".padEnd(12, ".") + total.toFixed(2));
Bread.......1.35
Milk........0.95
Apples......2.10
----------------
Total.......4.40

Every price here has one digit before the point, so they line up without padStart. For prices of £10 or more, add .padStart(6) after toFixed(2), as in example 4.

Your next step

Clear logs make every bug easier to find. Gwecode’s JavaScript Level 1 has you logging from the very first lesson, then teaches putting values inside text, tricks with text and what to do when code goes wrong, across 28 short lessons. Its level check is a tiny quiz game you build yourself. Every lesson is free and runs in your browser. Create a free account to keep your progress, and try the lesson below.

practise this · javascript · lessonPutting values inside textstart the lesson

questions

How do I log a number with two decimal places?

Call toFixed(2) on it and log the result, as in price.toFixed(2). It gives back text, rounded to two places, so use it for showing a value, not for further maths.

How do I log an object so I can read it?

Use JSON.stringify(obj, null, 2). The 2 indents each level by two spaces and puts every property on its own line. In a browser console you can also log the object itself and expand it with a click.

Why does my log say [object Object]?

You joined an object to text with +, which turns it into that placeholder. Pass it as a separate value with a comma, or use JSON.stringify.

Why is the month wrong when I log a date?

JavaScript counts months from 0, so new Date(2026, 10, 13) is 13 November, not October. Days of the month start at 1 as normal.

Should I remove console.log before publishing?

Yes, for logs you added while debugging. They clutter the console and can show data you did not mean to share. Keep only messages that are useful to whoever runs the code.

keep going.