To run and debug JavaScript files inside Visual Studio Code, execute files directly using the VS Code integrated terminal (node script.js) or Code Runner / Node.js run actions, and debug interactively by setting breakpoints in the gutter, opening the Run and Debug view (Ctrl+Shift+D / Cmd+Shift+D), and launching a launch.json Node.js configuration (or attaching to a running process) while validating inputs, runtime flags, and state maps safely with typeof / instanceof checks, Map, and try / catch blocks.
1. Running and Debugging JavaScript in VS Code (launch.json and Breakpoints)
Configure .vscode/launch.json for repeatable debugging with arguments, environment variables, and Node.js runtime validation, and inspect variables/call stacks at breakpoints inside try / catch:
// .vscode/launch.json configuration for debugging a JavaScript file in Node.js
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Current JS File",
"program": "${file}",
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"skipFiles": [
"<node_internals>/**"
]
}
]
}
// Example JavaScript entry file (sampleRunner.js) with validation, Map, and try/catch
function runDebuggableTask(configMap) {
if (!(configMap instanceof Map)) {
throw new TypeError("Expected configMap to be a Map instance.");
}
try {
const mode = configMap.get("mode");
const count = configMap.get("count");
if (typeof mode !== "string" || mode.trim().length === 0) {
throw new Error("Expected mode in configMap to be a non-empty string.");
}
if (typeof count !== "number" || !Number.isInteger(count) || count < 0) {
throw new RangeError("Expected count in configMap to be a non-negative integer.");
}
const resultsMap = new Map();
for (let i = 0; i < count; i += 1) {
resultsMap.set(`item_${i}`, `${mode.trim()}-${i}`);
}
return resultsMap;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Debug task failed: ${message}`);
}
}
// Set a breakpoint on the line below to inspect `outputMap` in the VS Code Variables pane
try {
const settings = new Map([
["mode", "trace"],
["count", 3]
]);
const outputMap = runDebuggableTask(settings);
console.log("Generated entries:", outputMap.size);
} catch (error) {
console.error(`${error.name}:${error.message}`);
}
- Click left of a line number in the editor gutter to toggle a red breakpoint before pressing
F5to start debugging. - Use
"console": "integratedTerminal"inlaunch.json: Allows interactivereadlineinput and clean ANSI log rendering.
2. Managing Multiple Launch Profiles and Debug Targets with a Map
When maintaining multiple debug scripts or environment profiles in tooling or test harnesses, map profile names to validated launch options inside a Map and wrap execution in try / catch:
// Resolve and validate named VS Code debug/run profiles from a Map
function getValidatedDebugProfile(profilesMap, profileName) {
if (!(profilesMap instanceof Map)) {
throw new TypeError("Expected profilesMap to be a Map instance.");
}
if (typeof profileName !== "string" || profileName.trim().length === 0) {
throw new TypeError("Expected profileName to be a non-empty string.");
}
try {
const key = profileName.trim();
if (!profilesMap.has(key)) {
throw new Error(`Debug profile "${key}" was not found in profilesMap.`);
}
const profile = profilesMap.get(key);
if (profile === null || typeof profile !== "object") {
throw new TypeError(`Profile "${key}" must be a non-null object.`);
}
if (typeof profile.program !== "string" || profile.program.trim().length === 0) {
throw new Error(`Profile "${key}" is missing a valid "program" path.`);
}
return {
name: key,
program: profile.program.trim(),
args: Array.isArray(profile.args) ? profile.args : []
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed resolving debug profile "${profileName}": ${message}`);
}
}
// Example usage:
// try {
// const debugProfiles = new Map([
// ["unit", { program: "scripts/runUnitTests.js", args: ["--verbose"] }],
// ["seed", { program: "scripts/seedDb.js", args: [] }]
// ]);
// console.log("Selected profile:", getValidatedDebugProfile(debugProfiles, "unit"));
// } catch (error) {
// console.error(`${error.name}:${error.message}`);
// }
- Use
Mapfor profile lookup: AvoidsObject.prototypecollisions on user-supplied profile keys. - Keep
<node_internals>/**inskipFiles: Stepping (F10/F11) stays focused on your application code rather than Node core internals.
3. Browser JavaScript vs. Node.js, Source Maps, and Debugging Caveats
Keep these VS Code JavaScript runtime differences in mind when running and debugging code:
- Node.js files do not have browser globals (
window,document,localStorage): Code referencingdocumentorwindowin a Node debug session throws aReferenceErrorunless executed in a browser/DOM environment or browser debugger. - Transpiled code (TypeScript / Babel / bundled JS) requires source maps: Enable source maps in your compiler/bundler so VS Code breakpoints map accurately to original source lines instead of compiled output.
- Check active workspace & Node version before launching: Run
node -vin the integrated terminal (Ctrl+\`` /Cmd+``) to confirm the expected Node.js runtime is active.
