JavaScript Setup: Install Node.js, VS Code & Write Your First Script
Before you write any real JavaScript, you need two things: somewhere to run it and somewhere to write it. This lesson gets you set up with both and walks you through your first working programs.
Three ways to run JavaScript
JavaScript can run in multiple environments. Understanding all three is important because you will use each one depending on what you are building.
1. The browser console
Every web browser has a built-in JavaScript console. This is the fastest way to try something:
- Open any web page (even a blank tab)
- Press
F12(orCtrl+Shift+Ion Windows/Linux,Cmd+Option+Ion Mac) - Click the Console tab
- Type
console.log("Hello!")and press Enter
You just ran JavaScript. The browser console is perfect for quick experiments, testing ideas, and debugging. But it is not where you write real programs.
2. A script tag in HTML
This is how JavaScript originally worked — embedded inside web pages:
<!DOCTYPE html>
<html>
<head>
<title>My First JS</title>
</head>
<body>
<h1 id="greeting">Hello</h1>
<script>
// JavaScript goes here
document.getElementById('greeting').textContent = 'Hello from JavaScript!';
console.log('Script loaded successfully');
</script>
</body>
</html>
The <script> tag tells the browser to execute JavaScript. You can also link to a separate file:
<script src="app.js"></script>
Important placement rule: Put your <script> tags at the bottom of <body>, or use the defer attribute. If the script runs before the HTML is parsed, it cannot find elements that have not been created yet:
<!-- Best practice: use defer -->
<script src="app.js" defer></script>
<!-- Or put at end of body -->
<body>
<!-- all your HTML here -->
<script src="app.js"></script>
</body>
3. Node.js (run JS without a browser)
Node.js lets you run JavaScript files directly from your terminal, like Python or Ruby scripts. This is how you build servers, CLI tools, and backend applications.
// save as hello.js
console.log('Hello from Node.js!');
console.log('Node version:', process.version);
console.log('Current directory:', process.cwd());
// run with: node hello.js
Install Node.js
Even if you only plan to write browser JavaScript, install Node.js. You need it for npm (the package manager), build tools, and running scripts.
Step 1: Download and install
Go to nodejs.org and download the LTS (Long Term Support) version. LTS is stable and recommended for most users. The “Current” version has newer features but may have bugs.
- Windows: Run the
.msiinstaller. Check all default options. - macOS: Run the
.pkginstaller, or use Homebrew:brew install node - Linux (Ubuntu/Debian):
# Install Node.js via NodeSource (recommended for latest LTS)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
# Or use nvm (Node Version Manager) for flexibility
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install --lts
Step 2: Verify the installation
Open a terminal and run:
node --version # should print something like v22.x.x
npm --version # should print something like 10.x.x
If both commands print version numbers, you are ready. If not, restart your terminal (or your computer on Windows) and try again.
What is npm?
npm (Node Package Manager) comes bundled with Node.js. It is how you install third-party libraries. Think of it like an app store for JavaScript code. We will use it extensively in later lessons, but for now, just know it is there.
Install VS Code
Visual Studio Code is the most popular code editor for JavaScript development. It is free, open source, and has excellent JavaScript support built in.
- Download from code.visualstudio.com
- Install and open it
- Install these recommended extensions (click the Extensions icon in the sidebar or press
Ctrl+Shift+X):- ESLint — catches common JavaScript mistakes as you type
- Prettier — auto-formats your code so it always looks clean
- Live Server — launches a local web server with live reload for HTML files
VS Code settings for JavaScript
Open settings (Ctrl+,) and set these:
- Format On Save: enabled — your code auto-formats every time you save
- Default Formatter: Prettier
- Tab Size: 2 spaces (JavaScript convention)
Your first real project
Let us build something real from scratch — not just a console.log, but a proper project structure.
Step 1: Create a project folder
mkdir my-first-js
cd my-first-js
Step 2: Create an HTML file
Create index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First JavaScript Project</title>
<style>
body {
font-family: system-ui, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
background: #1a1a1a;
color: #e0e0e0;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background: #00ff41;
color: #000;
border: none;
border-radius: 6px;
}
#output {
margin-top: 20px;
padding: 15px;
background: #111;
border: 1px solid #333;
border-radius: 8px;
font-family: monospace;
min-height: 50px;
}
</style>
</head>
<body>
<h1>JavaScript is alive!</h1>
<button id="btn">Click me</button>
<div id="output">Waiting for click...</div>
<script src="app.js"></script>
</body>
</html>
Step 3: Create the JavaScript file
Create app.js in the same folder:
// Get references to the HTML elements
const button = document.getElementById('btn');
const output = document.getElementById('output');
// Track how many times the button has been clicked
let clickCount = 0;
// Add an event listener — this runs when the button is clicked
button.addEventListener('click', function () {
clickCount++;
// Build a message
const messages = [
'JavaScript is running!',
'You clicked again! Keep going.',
'Three clicks! You are getting the hang of this.',
'Four clicks! Ready for the next lesson?',
'You really like clicking, huh?',
];
// Pick a message based on the click count (loop back after 5)
const messageIndex = Math.min(clickCount - 1, messages.length - 1);
const timestamp = new Date().toLocaleTimeString();
output.textContent = `[${timestamp}] Click #${clickCount}: ${messages[messageIndex]}`;
// Log to the console too (open DevTools to see this)
console.log(`Click #${clickCount} at ${timestamp}`);
});
// This runs immediately when the page loads
console.log('app.js loaded successfully!');
console.log('Open the Console tab in DevTools to see log messages.');
Step 4: Run it
Two options:
- Option A (Live Server): Right-click
index.htmlin VS Code and select “Open with Live Server.” The page opens in your browser with live reload. - Option B (manual): Just double-click
index.htmlto open it in your browser.
Click the button. Open DevTools (F12) and check the Console tab to see the log messages. Congratulations — you have a working JavaScript project.
Your first Node.js script
Now let us write something that runs on your computer, not in a browser:
// save as system-info.js
// Node.js has built-in modules for system access
const os = require('os');
console.log('=== System Info ===');
console.log('Platform:', os.platform()); // win32, linux, darwin
console.log('Architecture:', os.arch()); // x64, arm64
console.log('CPUs:', os.cpus().length);
console.log('Total RAM:', Math.round(os.totalmem() / 1024 / 1024 / 1024) + ' GB');
console.log('Free RAM:', Math.round(os.freemem() / 1024 / 1024 / 1024) + ' GB');
console.log('Home dir:', os.homedir());
console.log('Uptime:', Math.round(os.uptime() / 3600) + ' hours');
// Command-line arguments
console.log('\nArguments:', process.argv.slice(2));
// Run with: node system-info.js hello world
// Arguments: [ 'hello', 'world' ]
Run it: node system-info.js
The console object — your best debugging friend
console.log is the first tool every JavaScript developer learns, but the console object has much more:
// Basic logging
console.log('Normal message');
console.warn('Warning — something might be wrong');
console.error('Error — something IS wrong');
// Formatted output
console.log('Name: %s, Age: %d', 'Ada', 30);
// Objects get pretty-printed
console.log({ name: 'Ada', age: 30, skills: ['JS', 'Python'] });
// Tables (great for arrays of objects)
console.table([
{ name: 'Ada', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Cat', age: 35 },
]);
// Timing
console.time('loop');
for (let i = 0; i < 1000000; i++) {}
console.timeEnd('loop'); // loop: 3.45ms
// Group related logs
console.group('User Details');
console.log('Name: Ada');
console.log('Age: 30');
console.groupEnd();
// Count calls
function processItem() { console.count('processItem called'); }
processItem(); // processItem called: 1
processItem(); // processItem called: 2
// Assert (only logs if condition is false)
console.assert(1 === 1, 'This will NOT show');
console.assert(1 === 2, 'This WILL show because 1 !== 2');
// Clear the console
// console.clear();
Common setup mistakes and how to fix them
"node is not recognized as a command"
Node.js is not in your system PATH. On Windows, restart your terminal (or computer) after installation. On Linux/Mac, check if Node is installed in a non-standard location.
"Cannot find module" errors
You are trying to use a package you have not installed. Run npm install package-name in your project directory.
"Uncaught ReferenceError: document is not defined"
You are trying to use browser-only code (like document) in Node.js. Browser APIs do not exist in Node. Use console.log instead, or run your code in a browser.
"Unexpected token" syntax errors
Usually a typo — missing closing bracket, extra comma, or mismatched quotes. VS Code will underline syntax errors in red; look for the squiggly line.
Project structure best practices
As your projects grow, organize your files like this:
my-project/
├── index.html # Main HTML page
├── css/
│ └── style.css # Styles
├── js/
│ ├── app.js # Main JavaScript file
│ └── utils.js # Helper functions
├── images/ # Images and assets
└── README.md # Project description
For Node.js projects, the structure is slightly different:
my-node-project/
├── package.json # Project config and dependencies
├── src/
│ ├── index.js # Entry point
│ ├── routes/ # API routes
│ └── utils/ # Helper modules
├── tests/ # Test files
└── README.md
What to learn next
Your development environment is ready. You have run JavaScript in both the browser and Node.js. Next steps:
- Browser DevTools — master the tool you will use every day to debug, inspect, and profile your code.
- Variables (let, const, var) — learn how JavaScript stores and manages data.