2. Printing#

One of the first things you’ll want to do in JavaScript is display information on the console.

JavaScript provides a simple method to print messages to the console: console.log().

Try running the code below and play around with the message.

console.log("Hello from JavaScript!");

The syntax for console.log() is:

console.log(message);

Where:

  • console.log must be lowercase

  • message is the object to be printed, for example a string.

2.1. More Examples!#

Printing Numbers

console.log(42);

Printing Variables - More about variables on the next pages!

let name = "Alice";
console.log(name);

Combining Strings

console.log("I am " + 17 + " years old.");

2.2. Comments#

In the rest of this module we will use comments to help explain the code so let’s look at how they work.

JavaScript supports two types of comments: single-line comments and multi-line comments. Comments allow you to add notes or explanations to your code that are ignored when the program runs.

Single-Line Comments

These comments start with // and anything after that point is treated as a comment.

// This is a single-line comment
let age = 16; // This comment explains the variable

Multi-Line Comments

These comments start with /* and end with */. They can span as many lines as you like.

/*
This is a multi-line comment.
It can explain a more complex piece of code.
*/
let name = "Alice";

2.3. Common Printing Mistakes#

Don’t forget quotes for strings

console.log(Hello); // This will cause an error

Missing Parentheses

console.log "Hello"; // This will cause an error

Typos

JavaScript is case-sensitive, so Console.log() or console.Log() will not work.

2.4. Why Do We Use console.log()?#

When learning JavaScript, you might wonder why we use the full console.log() instead of just a simpler, single function like print in Python.

In JavaScript the console or terminal is represented by the globally available object console, which has many ways to show information. For example:

  • console.log(): displays general information.

  • console.warn(): displays a warning message.

  • console.error(): displays an error message.

The different types of printing reflect common situations that a browser encounters, such as a web developer using a deprecated function on a page, which might be presented as a warning. Likewise if something on the page isn’t compliant or crashes it should be shown as an error on the console.