How do you Run JavaScript Through the Terminal?
Running JavaScript through the terminal can be done in a few different ways, depending on the environment you’re using. Here are the most common methods:
Table of Content
Firstly, Make sure you have Node.js in your System. If you haven’t installed Node.js yet, you can download it from the official website: Node.js Downloads.
Using Node.js directly from terminal
- Open your terminal.
- Type node to enter the Node.js REPL (Read-Eval-Print Loop) environment.
node
- You can now type JavaScript code directly and execute it.
>const add = (a, b) => {
return a + b
}
console.log(add(4, 6))
Output:
10
Running JavaScript from a File
Step 1: Create a JavaScript file. Name this file as New.js.
// Function to add two variables.
const add = (a, b) => {
return a + b
}
console.log(add(4, 6))
Output
10
Step 2: Open your terminal or command prompt.
Step 3: Use the cd
command to navigate to the directory where your JavaScript file is located.
Step 4: Once you’re in the correct directory, run the script using the node
command followed by your script’s filename.
node New.js
Run the code in browser’s console
- Open Developer Tools, In most browsers (like Chrome, Firefox, or Edge), you can open the developer tools by pressing F12 or Ctrl+Shift+I.
- Click on the “Console” tab to open console window.
- You can type JavaScript code directly into the console and see the results immediately.
Conclusion
Running JavaScript through the terminal is straightforward and can be done using Node.js, a browser’s developer console. Node.js is the most commonly used method, especially for server-side or standalone JavaScript applications. For quick testing or debugging, the browser’s developer console or the Node.js REPL is also very handy.
JavaScript is best known for web page development but is also used in various non-browser environments. You can learn about JavaScript from the ground up by following JavaScript Tutorial and JavaScript Examples.