Skip to content
Laviyx Learn

Try

JavaScript course menu

Your First JavaScript Program: console.log, Statements and Errors

Write and run your first JavaScript program: printing with console.log, printing several values, numbers versus strings, running statements in order, and reading your first error messages.

Beginner4 min readUpdated
On this page

Programmers traditionally start a new language by printing "Hello, World!". In JavaScript, that takes one line.

Hello, World!#

hello.js (JavaScript)
console.log("Hello, World!");
Output
Hello, World!
  • console.log(...) prints whatever is inside the parentheses.
  • "Hello, World!" is a string: text inside quotes.
  • The line ends with a semicolon ;, which marks the end of a statement.

Run it with node hello.js, or paste it into your browser's console.

Several lines#

Statements run one after another, from top to bottom:

JavaScript
console.log("Step 1: boil water");
console.log("Step 2: add tea leaves");
console.log("Step 3: add milk and sugar");
Output
Step 1: boil water
Step 2: add tea leaves
Step 3: add milk and sugar

Printing numbers and calculations#

Numbers are written without quotes, and JavaScript calculates expressions before printing them:

JavaScript
console.log(42);
console.log(7 + 5);
console.log("7 + 5");
console.log(10 * 3, 10 / 4);
Output
42
12
7 + 5
30 2.5
  • 7 + 5 is a calculation, so it prints 12.
  • "7 + 5" is text in quotes, so it prints exactly as written.
  • console.log can print several values separated by commas; it puts a space between them.

Joining text#

The + operator joins strings together:

JavaScript
console.log("Good " + "morning");
console.log("Total: " + 250 + " rupees");
Output
Good morning
Total: 250 rupees

A cleaner way to mix text and values, template literals, is covered in Strings.

Your first errors#

Mistakes are normal. JavaScript reports them with an error message that says what went wrong and where.

Misspelling console gives a ReferenceError, because there is no variable called consol:

JavaScript
consol.log("Hi");
Output
ReferenceError: consol is not defined

Forgetting a closing quote or bracket gives a SyntaxError, and the program does not run at all:

JavaScript
console.log("Hi);
Output
SyntaxError: Invalid or unexpected token

Node.js also prints the file name and line number, and the browser console links straight to the line. Read the first line of an error carefully: it usually tells you exactly what to fix.

Practice#

Practice exercise

Write a program that prints:

Text
My shopping list
3 apples cost 90 rupees
Total items: 7

where 90 is calculated as 3 * 30 and 7 as 3 + 4 in the code.

Show solution
JavaScript
console.log("My shopping list");
console.log("3 apples cost " + 3 * 30 + " rupees");
console.log("Total items:", 3 + 4);
Output
My shopping list
3 apples cost 90 rupees
Total items: 7

* is calculated before +, just as in maths, so 3 * 30 is worked out first.

Key takeaway#

Finished this lesson?