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.
On this page
Programmers traditionally start a new language by printing "Hello, World!". In JavaScript, that takes one line.
Hello, World!#
console.log("Hello, World!");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:
console.log("Step 1: boil water");
console.log("Step 2: add tea leaves");
console.log("Step 3: add milk and sugar");Step 1: boil water
Step 2: add tea leaves
Step 3: add milk and sugarPrinting numbers and calculations#
Numbers are written without quotes, and JavaScript calculates expressions before printing them:
console.log(42);
console.log(7 + 5);
console.log("7 + 5");
console.log(10 * 3, 10 / 4);42
12
7 + 5
30 2.57 + 5is a calculation, so it prints12."7 + 5"is text in quotes, so it prints exactly as written.console.logcan print several values separated by commas; it puts a space between them.
Joining text#
The + operator joins strings together:
console.log("Good " + "morning");
console.log("Total: " + 250 + " rupees");Good morning
Total: 250 rupeesA 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:
consol.log("Hi");ReferenceError: consol is not definedForgetting a closing quote or bracket gives a SyntaxError, and the program does not run at all:
console.log("Hi);SyntaxError: Invalid or unexpected tokenNode.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:
My shopping list
3 apples cost 90 rupees
Total items: 7where 90 is calculated as 3 * 30 and 7 as 3 + 4 in the code.
Show solution
console.log("My shopping list");
console.log("3 apples cost " + 3 * 30 + " rupees");
console.log("Total items:", 3 + 4);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?