Internal: a <script> element within the HTML file.
HTML
<body>
<h1 id='msg'>Hello</h1>
<script>
console.log('Page loaded');
alert('Welcome!');
</script>
</body>External: a separate .js file (recommended).
HTML
<script src='js/app.js' defer></script>- Place the
<script>at the end of<body>, or in the<head>withdefer, so the HTML is loaded before the script runs (otherwisegetElementByIdreturnsnull). - Inline event attributes (
onclick='...') work but mix JS into HTML; preferaddEventListener(see 7.8.4).
Output and debugging tools
| Method | Use |
|---|---|
console.log(x) | Print to the browser console (F12, Console tab): your best debugging friend |
alert('hi') | Pop-up message |
prompt('Name?') | Pop-up asking for input; returns a string |
confirm('Sure?') | OK/Cancel; returns true or false |
document.write() | Writes into the page (avoid in real projects) |
element.textContent = ... | Change visible text (see DOM section) |
Comments: // single line and /* multi-line */. Statements end with a semicolon (recommended). JavaScript is case-sensitive: name and Name are different.