JavaScript lesson 1 of 9
JavaScript Printing and Output
Learn what console.log really does in JavaScript - string concatenation with +, template literals, printing multiple values, and the escape sequences you will use constantly.
Published · Every example on this page was run before it was published.
A program is silent by default. It can add up a thousand numbers, sort a list of names, and work out the exact cost of your shopping, and unless you tell it to say something you will see nothing at all. That is not a fault. A browser or a JavaScript runtime has no opinion about which of its internal results you care about, so it shows you none of them until you point at one and ask.
console.log is how you ask. It is the first thing almost everybody learns, and it stays useful
forever. It is how a finished program reports its results, and it is how you look inside a program
that is not doing what you expected. Long after you have learned loops and functions, console.log
is still the tool you reach for when something is wrong and you need to see what is actually
happening.
This lesson is about that one function, and about the quotes, concatenation, and template literals that surround it. None of it assumes you have written any code before. By the end you will be able to put text on the screen exactly where and how you want it, including multi-line blocks built from nothing but template literals.
What console.log Actually Does
console.log is a function — a piece of code that already exists inside JavaScript, ready for you
to use. You use a function by writing its name followed by a pair of round brackets, and whatever you
put between those brackets is handed over for the function to work with. Values handed over this way
are called arguments.
So console.log("Coffee is ready") gives one argument, the text Coffee is ready, to console.log,
and console.log writes it to the screen.
console.log("Coffee is ready");Coffee is readyNothing else happens. JavaScript read the line, did what it said, and moved on. That is worth stating plainly, because the opposite case surprises people: a line that calculates something but never logs it produces no output whatsoever.
5 + 3;
"a line of text sitting on its own";
console.log(5 + 3);8The first line added 5 and 3. JavaScript genuinely did that addition — it just had nowhere to put the
answer, so the answer was thrown away. The second line is a piece of text that nobody asked to see.
Only the third line, the one wrapped in console.log, reaches the screen. When you run a program and
see nothing, this is almost always why: the work happened, and nobody asked for the result.
Each console.log finishes the line it wrote, which is why the next one begins underneath rather than
alongside, and several console.log calls stack up in the order you wrote them.
console.log("Kettle on");
console.log("Water boiling");
console.log("Tea poured");Kettle on
Water boiling
Tea pouredThree statements, three lines of output, top to bottom. JavaScript does not reorder anything and does not tidy anything up. Also notice the semicolon at the end of each line. JavaScript does not strictly require one there — a feature called automatic semicolon insertion will often add it for you — but relying on that is a good way to be surprised later, so this site's examples end every statement with one deliberately.
Quotes Turn Words Into Text
Look again at what went inside the brackets: "Coffee is ready", with a quotation mark at each end.
Those quotes are not decoration. They are how you tell JavaScript that the characters between them are
a piece of text to be taken literally, rather than the name of something in your program. Text handled
this way is called a string, because it is a run of characters threaded together in order.
JavaScript accepts three ways to delimit a string: single quotes, double quotes, and backticks. Single and double quotes behave identically, so pick whichever you prefer and stay consistent. Backticks are different and more powerful — they are covered in their own section below.
console.log('Single quotes are fine');
console.log("So are double quotes");Single quotes are fine
So are double quotesWhat matters is that the quote at the end matches the quote at the start.
Take the quotes away and the meaning changes completely:
console.log(Hello);ReferenceError: Hello is not definedWithout quotes, Hello is no longer text — it is a name, and JavaScript goes looking for a
variable in your program called Hello. There is nothing by that name, so it stops and says so. A
ReferenceError always means the same thing: you referred to something JavaScript has never been
introduced to. When the thing you meant was a piece of text, the fix is quotes around it.
Putting a Quote Inside a String
An apostrophe is a single quote character, which creates an obvious problem if single quotes are also what marks the start and end of your string. There are two clean ways out, and you will use both.
console.log("It's nearly five o'clock");
console.log('She said "good morning" and walked on');
console.log('It\'s nearly five o\'clock');It's nearly five o'clock
She said "good morning" and walked on
It's nearly five o'clockThe first line wraps the text in double quotes, so the apostrophe inside is just another character. The second does the reverse: single quotes on the outside leave double quotes free to appear inside. This is the practical reason JavaScript offers more than one quote style rather than just one.
The third line shows the other approach. A backslash immediately before a quote tells JavaScript that this particular quote belongs to the text and does not end the string. A backslash used this way is called an escape character, because it changes the meaning of the character that follows it. Switching to a different quote style is usually easier to read, but the backslash always works — including when both kinds of quote appear in the same sentence.
Printing Several Values at Once
console.log accepts more than one argument. Separate them with commas and they all land on the same
line.
console.log("Guests:", 23);
console.log("red", "green", "blue");Guests: 23
red green blueNotice what JavaScript did between them: it inserted a single space. You did not type that space, and
it appears between every adjacent pair of values. This is a deliberate convenience, and it is why
console.log("Guests:", 23) reads correctly without you having to think about spacing at all.
It also means that typing your own space gets you two.
console.log("Total:", 99);
console.log("Total: ", 99);Total: 99
Total: 99The second line has a space you typed inside the quotes and a space console.log added, one after the
other. When a gap in your output looks slightly too wide, this is usually the cause.
Joining Text with +
The other way to build a line of output is to join pieces of text yourself, before they ever reach
console.log. The + operator does that job for strings, gluing the text on its right onto the text
on its left.
console.log("Guests: " + 23);Guests: 23Notice something that would be an error in many languages: "Guests: " is a string and 23 is a
number, and + joined them anyway. JavaScript's + operator is happy to work with a mix, and when
either side is a string it converts the other side to text automatically rather than complaining. That
convenience is also a trap, and it is worth seeing exactly how it behaves before it surprises you.
+ always reads strictly left to right, and it decides what to do at each step based on what it has
so far — not on what comes later in the line:
console.log("Items: " + 3 + " bags");
console.log(3 + 4 + " apples");
console.log("Apples: " + 3 + 4);Items: 3 bags
7 apples
Apples: 34Read each line as JavaScript does, one + at a time. On the first line, "Items: " + 3 is a string
next to a number, so it concatenates to "Items: 3", and adding " bags" onto that string continues
concatenating. On the second line, 3 + 4 is two numbers, so it adds to 7 first — only once that 7
meets the string " apples" does concatenation begin, giving "7 apples". The third line starts
concatenating immediately, so "Apples: " + 3 becomes the string "Apples: 3", and the following + 4 concatenates again rather than adding, giving "Apples: 34" instead of the "Apples: 7" you might
have expected. Once a + chain turns into a string, every + after it stays a concatenation, even
where a number appears.
Template Literals
Stitching values into a sentence with + gets noisy fast, and the order-dependent behaviour above
makes it easy to get wrong. JavaScript's better tool is the template literal: a string delimited by
backticks (`) instead of quotes, which lets you drop a value directly into the text using ${}.
const name = "Maya";
const apples = 4;
console.log(`I have ${apples} apples, ${name}.`);
console.log(`Next month I will have ${apples + 12} apples.`);I have 4 apples, Maya.
Next month I will have 16 apples.Anything between the ${ and the matching } is a real JavaScript expression. JavaScript evaluates
it, converts the result to text, and inserts it exactly where the braces were — apples + 12 is worked
out as 16 before it ever becomes part of the string. This is unambiguous in a way + chaining is
not, because each value is marked out explicitly rather than inferred from left-to-right order.
Template literals also span multiple lines without any escape sequences at all. Whatever you type between the backticks — including line breaks — is kept exactly as typed:
console.log(`Corner Cafe
17 Mill Lane
Open until six`);Corner Cafe
17 Mill Lane
Open until sixBecause they are unambiguous and easy to read, template literals are the standard way to build output
in modern JavaScript. Reach for + only for very short joins; reach for a template literal the moment
more than one value is involved.
Escape Sequences
Sometimes you need a character you cannot simply type between quotes — a newline, or a tab. For those cases, JavaScript uses an escape sequence: a backslash followed by a letter, which together stand for one special character. These work the same way inside single quotes, double quotes, and backtick template literals.
console.log("Line one\nLine two");
console.log("Name\tScore");
console.log("Ada\t91");
console.log("Saved to C:\\reports\\july.txt");Line one
Line two
Name Score
Ada 91
Saved to C:\reports\july.txt\n starts a new line in the middle of a string, which means one console.log call can produce
several lines of output. \t is a tab, which is a quick way to get two columns roughly lining up. And
\\, two backslashes, produces one literal backslash — which you need whenever a backslash is
genuinely part of your text, as in a Windows file path. That last one exists because the backslash has
been given a job: once a character means "change the meaning of the next character," it needs an
escape sequence of its own in order to mean itself again.
A Worked Example
Here is a small receipt, produced entirely by console.log — no library, nothing you have not met on
this page.
const item = "Flat white";
const price = 3.2;
const quantity = 2;
console.log("======================");
console.log(" CORNER CAFE");
console.log("======================");
console.log(item, "x", quantity);
console.log(`Price each: $${price}`);
console.log(`Total: $${price * quantity}`);
console.log("======================");======================
CORNER CAFE
======================
Flat white x 2
Price each: $3.2
Total: $6.4
======================Reading it from the top: the rows of = are ordinary text inside quotes, doing the job of a ruled line
on a paper receipt — JavaScript has no idea they are meant to look like a border, the shape exists only
in your eye. console.log(item, "x", quantity) uses the comma form from earlier in this lesson, so
console.log supplies the spaces between "Flat white", "x", and 2 for you.
The last two lines before the closing border use template literals instead, because each one needs to
mix a fixed label with a calculated value. ${price} drops in 3.2 exactly as stored, and ${price * quantity} computes 3.2 * 2 before inserting it — JavaScript always evaluates the expression inside
${} completely before it becomes part of the string, the same way it evaluates any other expression
before handing it to console.log.
Common Mistakes
Forgetting to switch to backticks
const name = "Sam";
console.log("Hello, ${name}!");Hello, ${name}!The ${name} syntax only means something inside backticks. Inside ordinary single or double quotes it
is just four characters — a dollar sign, curly braces, and the letters name — with no special
meaning at all, so it prints exactly as typed instead of being replaced. The fix is to change the outer
quotes to backticks: `Hello, ${name}!`.
Expecting + to leave a space
console.log("Hello" + "World");
console.log("Hello", "World");HelloWorld
Hello World+ joins two strings with nothing in between, exactly as written. The automatic single space belongs
to the comma form of console.log, not to string concatenation. If you want a space with +, you have
to include it yourself, inside one of the strings or as a third piece.
Trusting + to keep adding once a string appears
console.log(1 + 1 + "2");
console.log("2" + 1 + 1);22
211The first line adds the two numbers first, giving 2, and only then concatenates that 2 onto the
string "2", giving "22". The second line starts with a string, so every + after it concatenates —
"2" + 1 is "21", and "21" + 1 is "211", with no addition happening anywhere. Whenever +
produces a surprising result, work through it left to right exactly as JavaScript does, and check
whether a string has already appeared by the time a number joins in. This is exactly the kind of
ambiguity template literals exist to remove.
Next Steps
The linked practice problem, reverse-words-in-a-string, is a clear step up from anything on this
page, and that is deliberate. Every attempt you make at it will be checked by printing the result, and
every time the result comes out wrong, console.log is how you find out which part of the string went
astray. Printing is not a beginner topic you leave behind — it is the instrument you debug with for the
rest of your programming life.
Before that, spend ten minutes in the JavaScript playground. Log a
value, then log several separated by commas and watch the spacing. Build the same line two ways, once
with + and once with a template literal, and notice which one you trust more once the values get
complicated. Then delete a closing backtick on purpose, so that you recognise the error it produces on
sight when it turns up for real.
When you want a harder one
Interview-style problems graded against hidden tests — a big step up from the exercises. Come back to these when the ideas in this lesson feel comfortable rather than new.