3.1 Hello JavaScript
A program is a set of precise instructions that asks a computer to solve a problem. JavaScript is the programming language built into every modern browser. HTML describes the page structure, CSS describes the look, and JavaScript describes behavior: what should happen when data changes or the user clicks, types, scrolls, or submits a form.
At first, think of a JavaScript program as a sequence of steps. The browser reads those steps from top to bottom, runs each statement, and can update the page while it runs.
What JavaScript can do in a page
Most JavaScript programs combine the same four basic actions used in other programming languages:
- Input: read data from a form field, button click, URL, file, server response, or
prompt(). - Processing: calculate, compare, transform, or store data.
- Output: print to the console, show an alert, or update the DOM so the page changes.
- Control flow: decide what runs first, what repeats, and what only runs when a condition is true.
These ideas are not unique to JavaScript. Python, C, Java, and JavaScript all share them; only the syntax and runtime environment differ.
Your first JavaScript program
Hello World is usually the first program in a new language. In JavaScript, the simplest version prints text to the browser console:
console.log("Hello World!");Output:
Hello World!There are three details to notice:
console.logprints a value to the developer console.- Parentheses
()pass data into the function. "Hello World!"is a string, which means text wrapped in quotes.
You can read the line as: "call console.log, and print the string Hello World!."
Running JavaScript
There are three beginner-friendly ways to run JavaScript:
1. Open browser developer tools, switch to Console, type JavaScript, and press Enter. 2. Write JavaScript inside a page with <script> ... </script>. 3. Put JavaScript in a separate .js file and connect it with <script src="script.js"></script>.
For example:
<!DOCTYPE html>
<html>
<body>
<h1>Hello JavaScript</h1>
<script>
console.log("The page loaded!");
</script>
</body>
</html>For larger pages, use a separate file:
<script src="script.js"></script>// script.js
console.log("Hello from a separate file!");Comments
Comments are notes for humans. They are ignored by JavaScript when the program runs.
Common JavaScript comment styles:
- Single-line comments start with
//. - Multi-line comments are wrapped in
/* ... */.
console.log("Hello World!"); // print a greetingUse comments to explain intent, not to repeat obvious code.