Your First JavaScript: Running Code in the Browser
JavaScript is a programming language. A programming language is a set of instructions you write so a computer can do things. Browsers like Chrome, Firefox, and Safari all understand JavaScript. That makes it the main language of web pages.
In this chapter, you will run your very first JavaScript code. No setup needed — just a browser.
Where You Type JavaScript
Every modern browser has a developer console. The console is a place where you can type JavaScript and see the result immediately.
To open it:
- Right-click anywhere on a web page.
- Click Inspect.
- In the panel that opens, click the Console tab.
You can also press F12 on Windows, or Option + Command + J on a Mac.
Your First Line of Code
Click in the console, type this, and press Enter:
console.log("Hello, world!");You should see Hello, world! printed back to you.
Here is what that line does:
console.log(...)is a function call. A function is a named piece of code that does a job. This one prints things to the console."Hello, world!"is a string. A string is text wrapped in quotes.
Try changing the text between the quotes and running it again. You can also do math:
console.log(2 + 3);
console.log("2 + 3");The first prints 5. The second prints the literal text 2 + 3, because quotes mean "this is text, do not calculate it."
Three Ways JavaScript Runs
JavaScript code can live in a few places. It is worth knowing all three.
- The console — great for quick tests, like this chapter.
- Inline in HTML — code written inside a
<script>tag in an HTML file. - A separate file — a file like
script.jslinked from your HTML with<script src="script.js"></script>. This is how real websites do it.
<!DOCTYPE html>
<html>
<body>
<h1>My page</h1>
<script src="script.js"></script>
</body>
</html>The browser loads the page, finds the script, and runs it from top to bottom, one line at a time. This matters: if line 1 has an error, the browser stops there and prints an error to the console.
Show diagram source
graph LR
A[Browser loads HTML] --> B[Finds script tag]
B --> C[Reads JS line by line]
C --> D{Works?}
D -- yes --> E[Output appears]
D -- no --> F[Error in console]Experiment Freely
The console is safe. You cannot break your computer or the website you are on — refresh the page and everything resets. Try arithmetic, strings, and console.log with different things. Mistyping is how you learn.
Exercise
You run console.log("5 * 5"). What is printed, and why?
Show answer
The text 5 * 5. Because it is inside quotes, it is a string (text), not a calculation. Removing the quotes would print 25.
Exercise
Where do you look in the browser to see JavaScript error messages?
Show answer
The developer console (F12, or Inspect > Console). Errors appear there in red.
Spotted a mistake, or code that does not work?