Introduction to JavaScript
HTML gives a page structure and CSS gives it style. JavaScript adds behaviour: it can respond to clicks, change content, validate forms and much more. It is the programming language of the browser, and this lesson shows how to run your first scripts.
Adding JavaScript to a page
Scripts live inside a <script> tag. You can write code directly between the tags, but it is cleaner to keep it in a separate file and link it with the src attribute. Place the script just before the closing body tag so the HTML has loaded first.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>My page</title>
</head>
<body>
<h1>Hello</h1>
<script src='app.js'></script>
</body>
</html>
Statements and comments
A program is a list of statements, usually one per line and ending in a semicolon. Comments are notes the browser ignores: use two slashes for a single line, or the slash-star pair for a block.
// this is a single-line comment
let score = 10; // set a value
/* this is a
block comment */
Output for learning
Two simple ways to see what your code is doing:
console.log('text')prints to the browser developer console, which you open with the F12 key. This is the tool you will use most while learning.alert('text')pops up a message box. It is handy for quick tests but annoying in real sites.
console.log('The page has loaded');
let name = 'Aisha';
console.log('Welcome ' + name);
The plus sign joins pieces of text together, which is called concatenation.
Case sensitivity and good habits
JavaScript is case sensitive, so myScore and myscore are different names. Since ES6 you should declare variables with let or const, never the older var. Use clear names and keep one statement per line so your code stays readable.
How the browser runs your code
The browser reads your script from top to bottom and runs each statement in order. If it meets a mistake it cannot understand, such as a missing bracket, it stops and reports an error in the console. That is why the console is your best friend while learning: when something does not work, open it first and read the red message, which names the file and line where the problem is. Fixing one error at a time, then reloading the page, is the normal rhythm of writing JavaScript.