JavaScript Tutorial for Beginners: First Program
JavaScript is the programming language built into every web browser. It makes pages interactive: menus that open, forms that check input, maps that move. The same language also runs outside the browser through Node.js, where it powers servers and command-line tools. The language is standardized as ECMAScript; the yearly editions are named ES2015, ES2016 and so on.
Your first program
console.log() writes values to the console, a text panel for developers. It is the JavaScript equivalent of Python's print(), and the first debugging tool everyone uses. Several values separated by commas are printed with a space between them.
Expected output
Hello from JavaScript! 2 + 3 = 5 28 string number
Press Run. The code executes in a sandboxed frame inside this page, and anything sent to console.log() appears below the editor. Edit the text, add a line, and run it again.
What the example shows
- Text values, called strings, are written in quotes.
2 + 3is evaluated before printing..lengthis a property of a string that holds its number of characters, spaces included.typeofreports the type of a value; you will meet all the types in the data types chapter.
Statements usually end with a semicolon. JavaScript can insert missing semicolons automatically, but the rules have edge cases, so most style guides tell you to write them yourself.
Where JavaScript runs
In a web page, code lives inside a <script> element or in a separate .js file loaded with <script src="app.js"></script>. To experiment on any site, open the browser's developer tools (F12, or Cmd+Option+J in Chrome on a Mac) and type into the Console tab. With Node.js installed, save code to hello.js and run node hello.js in a terminal.
Common mistakes
- Typing
console.LogorConsole.log. JavaScript is case-sensitive. - Using curly "smart" quotes pasted from a word processor; only straight quotes work.
- Confusing JavaScript with Java. Despite the name, they are unrelated languages.
Summary
- JavaScript runs in every browser and, via Node.js, on servers.
console.log()prints values to the console, separated by spaces.- Strings go in quotes; end statements with semicolons.
Quiz: Get started