Your First JavaScript Code
Writing your first line of JavaScript is an exciting step! It’s where your code starts to come to life and interact with the web page. In this lesson, you’ll learn how to write simple code, save it in a file, and connect it to a basic HTML page so it runs in the browser.
Using console.log()
The console.log()
function is one of the easiest ways to see what your code is doing. Think of it like talking to the browser—it prints messages to the console so you can understand what’s happening behind the scenes.
Try typing this in your browser console or a .js
file:
console.log("Hello, world!");
When you run it, you’ll see “Hello, world!” appear in the console. This is how developers test their code, check values, and debug problems.
Writing and saving your first .js file
To start writing JavaScript on your own, open your code editor (like VS Code) and create a new file called script.js
. Then write this code:
console.log("This is my first JavaScript file!");
Save the file. That’s it—you’ve just written a real JavaScript file!
Linking JS to an HTML file
To see your JavaScript work in a browser, you need to connect your .js
file to an HTML file. Create a new file called index.html
and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>My First JS Project</title>
</head>
<body>
<h1>Hello from HTML</h1>
<script src="script.js"></script>
</body>
</html>
Now open index.html
in your browser. Open the console (F12
or right-click → Inspect → Console), and you’ll see the message from your .js
file appear. This shows that your JavaScript is running correctly.