Running JavaScript Code
There are two primary ways to run JavaScript files locally once your environment is set up.
1. Running JS in the Browser
To run your code in a browser, you need to connect your .js file to an HTML document using the <script> tag.
Step 1: Create index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My JS App</title>
</head>
<body>
<h1>Hello World</h1>
<script src="app.js"></script>
</body>
</html>
Step 2: Create app.js
console.log("JavaScript is running in the browser!");
Step 3: Open index.html in your browser and check the developer console!
2. Running JS via Node.js
Running code via Node.js means you bypass the browser entirely. Since there's no browser, there's no DOM (Document Object Model), meaning you cannot manipulate HTML.
Step 1: Open your terminal and create a file.
// main.js
console.log("JavaScript is running locally via Node!");
Step 2: Execute the file using the node command.
node main.js