How to run JavaScript in a terminal
JavaScript is a versatile programming language that can be used in various environments. Initially, JavaScript was commonly used in browsers to add interactivity to web pages. Now, it is used by clients and servers to provide dynamic, engaging, and interactive user experiences across several platforms, such as mobile applications, smart devices, desktop applications, wearables, and more.
A terminal is a text-based interface on the computer where commands can be run to manipulate files, view folders and files, execute programs, navigate the directory, open files, and more.
The default terminal on Mac and Linux is called Terminal, and on Windows, it is the Command Prompt. Windows PowerShell can also be used on Windows. Several Integrated Development Environments (IDEs), such as VS Code, also have an integrated terminal.
Javascript can be run in the terminal using the Node.js environment.
Steps
If Node.js is not installed on your system, you can download and install it for your operating system from the
. The recommended version on the official website is ideal as it is the most stable version.official website https://nodejs.org/en/download Confirm successful installation of Node.js by running the
node -vornode --versionto print out the node version. If it successfully prints the version, then Node.js was successfully installed. Let's try this command in the following terminal.
Create a file with the JavaScript code to be run and add a
console.logstatement to ensure getting an output in the terminal.Navigate to the file path in the terminal using the
cdcommand.Run the code in the terminal by entering
node <filename>.js. For example, if the filename ishello, the command would benode hello.js. Let's run this command in the following terminal, and we will get"Hello World"as output.
When to run JavaScript in the terminal
These are some of the scenarios where we can run JavaScript in the terminal.
When learning a new JavaScript concept, such as loops, closure, or recursion, running the code in a terminal is useful in understanding the concepts and how they work.
When debugging a code, printing to the terminal is helpful.
Conclusion
A Node.js environment is required to run JavaScript in the terminal and the code can be run by using the node command with the root filename.