How to run JavaScript code inside Visual Studio Code

Here's the most simple way to run JavaScript using Visual Studio Code

Posted on April 02, 2021


Sometimes, you may want to run your JavaScript code immediately inside Visual Studio Code (VSCode) just to see if a piece of code works. The easiest way to run JavaScript using VSCode usually involves installing Node.js locally on your machine so that you can call the script using Node.js.

For example, suppose you have a script called index.js with the following code:

function factorial(num) {
  if (num === 0 || num === 1) {
    return num;
  }
  return num * factorial(num - 1);
}

let n = factorial(8);
console.log(n); // 40320

To run the file, you first need to open the integrated VSCode terminal in View > Terminal menu command:

Opening VSCode terminal
Opening VSCode terminal

Once inside the terminal, you can then run the code using node name_of_file.js command. The picture below shows the result of running node index.js command on the terminal:

Run JavaScript code in VSCode terminal
Run JavaScript code in VSCode terminal

By using Node.js, you can test run any simple JavaScript code you’ve written easily from VSCode integrated terminal.

Using Code Runner Extension

Alternatively, you can also use the VSCode Code Runner Extension to run JavaScript code without having to open the console and call Node.js manually.

After you installed the extension, you just need to open the context menu on the JavaScript file you want to run with right-click, then click on the Run Code menu:

Run JavaScript code using Code Runner
Run JavaScript code using Code Runner

But internally, Code Runner also looks for Node.js that’s installed on your local machine, so you need to install Node.js either way.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more