Writing Your First JavaScript Program
Once Node.js is installed and you understand where JavaScript runs, the next step is writing your first program. You can write JavaScript code in two main environments: directly in the browser or using Node.js on your system.
Writing JavaScript in the Browser
The browser is the simplest place to start. You can add JavaScript inside an HTML file using the <script>
tag.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My First JS Program</title>
</head>
<body>
<h2>Open your browser console</h2>
<script>
console.log("Hello, JavaScript!");
</script>
</body>
</html>
How to Run It:
- Save the file as
index.html
. - Open it in any browser.
- Right-click > Inspect > Go to the Console tab.
- You’ll see: CopyEdit
Hello, JavaScript!
This is how browsers run your JavaScript — it’s part of the webpage.
Writing JavaScript in Node.js
You can also write JavaScript in standalone .js
files and run them using Node.js through the terminal.
Example:
Create a file named app.js
:
console.log("Hello from Node.js!");
Run it using:
node app.js
You’ll see the output in your terminal:
Hello from Node.js!
This method is useful when you’re building backend tools, APIs, or running automation scripts.
JavaScript Output Methods
There are several ways to show output in JavaScript, depending on the environment:
Method | Usage Area | Description |
---|---|---|
console.log() | Both Browser & Node | Logs to console or terminal |
alert() | Browser only | Pops up an alert box |
document.write() | Browser only | Writes directly into the HTML |
Example using alert()
:
<script>
alert("Welcome to JavaScript!");
</script>
Use alert()
only for simple messages or debugging — not for real applications.
Tools for Writing JavaScript
You can write JavaScript using any text editor. Popular choices include:
- Visual Studio Code (recommended)
- Sublime Text
- Atom
- Notepad++
Even basic Notepad will work, though it lacks helpful features like syntax highlighting and linting.
Summary
You can run JavaScript code directly in a browser using the <script>
tag or in your terminal using Node.js. Start with simple messages like console.log("Hello")
to understand how code executes. From here, you can begin exploring variables, conditions, and logic.