In this lesson: Run JavaScript in a page and in the browser console.
HTML is structure. CSS is appearance. JavaScript is behaviour — it is a real programming language, and it is what makes a page respond to people.
Adding it to a page
<!-- best: an external file, just before </body> -->
<script src="/js/app.js"></script>
<!-- or inline, for a quick test -->
<script>
console.log('Hello from JavaScript');
</script>
Put the <script> just before the closing </body> tag. If it runs before the HTML exists, your code will not find the elements it wants. (The alternative is <script src="..." defer> in the head, which waits for the document.)
The console is your workshop
Press F12 in your browser and open the Console tab. You can type JavaScript straight into it and see the result immediately. Try:
2 + 2
'Yanjye'.toUpperCase()
console.log('It works');
Statements and comments
let name = 'Aline'; // a single-line comment
/*
A comment spanning
several lines
*/
Semicolons end statements. JavaScript will insert them for you in most cases, but writing them yourself avoids a small class of genuinely confusing bugs.
Case matters
myName, myname and MyName are three different things. JavaScript convention is camelCase for variables and functions.