The function console.log is a built-in JavaScript tool. When you hear something like “log it to the console” or “print it to the screen”, that’s a reference to using console.log.

Using console.log to print “Hello, world!”

console.log("Hello, world!");

After running this code, you’ll see the string Hello, world! on the screen.

Changing the text in console.log

You can easily change the text you’re printing by editing the part between the quotes.

console.log("It works!");

Printing multiple strings to the screen with console.log

You can also add more console.log statements to your program to print multiple strings to the screen.

console.log("Great!");
console.log("Now I can print multiple strings to the screen!");

Common beginner mistakes

As a beginner in JavaScript, it’s natural to make some common mistakes while learning. Don’t worry. Mistakes are a natural part of the learning process! Understanding these common pitfalls when using console.log will help you avoid frustration and progress faster in your coding journey.

Let’s explore some of the typical mistakes beginners make when printing strings to the screen with console.log:

1. Forgetting parentheses with console.log

When using console.log to print something to the console, it’s crucial to remember the parentheses. Forgetting them will result in the function not executing correctly, and you won’t see the output you expect.

Incorrect:

console.log "Hello, World!";  // Missing parentheses

Correct:

console.log("Hello, World!"); // Parentheses are present

2. Missing Quotation Marks

String literals should always be enclosed within quotation marks. Forgetting to add them will result in a syntax error.

Incorrect:

console.log(Hello, World!); // Missing quotation marks

Correct:

console.log("Hello, World!"); // String enclosed in quotation marks

3. Mixing quotation marks of different types

Mixing quotation marks of different types is a common mistake that beginners might encounter in JavaScript. In JavaScript, strings can be enclosed either in single quotes (' ‘), double quotes (" “), or backticks (``). While all three options are valid, using mismatched quotation marks within the same code can lead to syntax errors.

Incorrect:

console.log('Hello, World!"); // Mismatched quotes
console.log("Hello, World!`); // Mismatched quotes

Correct:

console.log('Hello, World!'); // Matching single quotes
console.log("Hello, World!"); // Matching double quotes
console.log(`Hello, World!`); // Matching backticks

It’s essential to use the same type of quotation marks for a string throughout your code.