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:
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:
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:
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.