Introduction to JavaScript
JavaScript is the programming language that brings web pages to life: it reacts to clicks, validates forms and loads data without a page reload. It is built into every browser, so there is nothing to install to get started.
Where JavaScript runs
JavaScript originally ran only in the browser — right on the visitor's computer. Today it also runs on servers with Node.js, so both the interface and the back end can be written in one language.
The examples in this tutorial run in your browser. Press "Run" under any of them, then try changing the code and running it again.
Your first program
The console.log() command prints the value passed to it in parentheses. In a browser the result goes to the developer console; here it appears in the block under the example:
console.log('Hello, world!'); // Hello, world!Text in quotes is called a string. The comment // Hello, world! on the right shows what the program prints — every example in this tutorial is written this way.
Numbers and calculations
Besides text, console.log() can print numbers. Numbers are written without quotes, and you can calculate with them right away:
console.log(2 + 3); // 5JavaScript first evaluates the expression 2 + 3 and then prints the result. If you put a number in quotes, it becomes a string and is printed as text.
Several statements
A single command of a program is called a statement. Statements run in order, from top to bottom, and by convention each one ends with a semicolon. Every console.log() call prints a new line:
console.log('First line'); // First line
console.log('Second line'); // Second lineYou can print several values at once, separated by commas — they are joined with a space:
console.log('I am', 25, 'years old'); // I am 25 years oldComments
A comment is a note in the code that JavaScript skips. A single-line comment starts with //; a multi-line one goes between /* and */:
// A single-line comment
/*
A multi-line
comment
*/
console.log('Comments are not printed'); // Comments are not printedA good comment explains why the code exists rather than restating what it does.
Common mistake
JavaScript is case-sensitive: console.log and Console.Log are different names. A typo in the case causes an error, and the program stops at that line:
Console.log('Hello'); // ReferenceError: Console is not definedIf an example does not work, first compare the letters in the names with the original.