How To Run Javascript In Terminal

JavaScript is primarily known for its use in web browsers, but it isn’t limited to that environment. You can also run JavaScript code directly in your terminal using a runtime environment called Node.js. In this blog post, we will take a look at how to set up and run JavaScript in your terminal using Node.js.

Setting up Node.js

To run JavaScript in your terminal, you’ll need to have Node.js installed on your computer. You can download the latest version of Node.js from the official website: Simply follow the installation instructions for your operating system (Windows, macOS, or Linux). Once installed, you can check if Node.js is correctly installed by running the following command in your terminal:

node -v

If Node.js is installed correctly, you should see the version number printed in the terminal.

Running JavaScript in Terminal

Now that you have Node.js installed, it’s time to run some JavaScript code in your terminal! There are two main ways to run JavaScript code using Node.js: running a script file and executing code directly in the terminal.

Running a Script File

To run JavaScript code from a script file, first, create a new text file and save it with a .js extension (e.g., myScript.js). Open the file in your favorite text editor and write some JavaScript code. For example, let’s create a simple script that prints “Hello, World!” to the console:

// myScript.js
console.log("Hello, World!");

Save the file, and then open your terminal in the same directory where the script is saved. To run the script, simply type the following command:

node myScript.js

The output of the script (“Hello, World!”) should appear in the terminal.

Executing Code Directly in the Terminal

If you want to quickly test some JavaScript code without creating a script file, you can run the code directly in your terminal using the Node.js REPL (Read-Eval-Print Loop). To start the REPL, simply type node in your terminal and press Enter. You should see a > prompt, indicating that you’re in the Node.js REPL:


Now you can type any JavaScript code you’d like to test, and the REPL will evaluate it and print the result. For example:

> console.log("Hello, World!")
Hello, World!
> 2 + 3

To exit the Node.js REPL, press Ctrl + C twice or type .exit and press Enter.

Wrapping Up

In this blog post, we’ve covered how to run JavaScript code in your terminal using Node.js. By installing Node.js and utilizing script files or the REPL, you can quickly and conveniently work with JavaScript outside of the web browser environment. This is particularly useful for tasks such as building command-line tools, server-side applications, and working with various APIs.