JavaScript

How to Get User Input from Command Line With JavaScript

Sometimes, there is a need to utilize JavaScript from the command line. However, the command prompt does not allow the use of the JavaScript program. For that purpose, JavaScript provides the “prompt()” method which works exactly the same on the command line. Furthermore, you can also use Node.js for this purpose.

This post will state the method for getting the user input from the command line with the help of JavaScript.

How to Get User Input from Command Line With JavaScript?

To get the user input from the command line with JavaScript, we will use the prompt method that displays a dialog box that prompts the user for input. The “prompt()” method returns the entered value if the user clicks “OK”.

For practical implications, check out the stated example.

Example 1: Get a Single Value Using prompt() Method
You can get the user input from the command line with JavaScript. To do so, declare a constant type object and utilize the “prompt()” method that will return the user input when the user clicks on the “OK” button:

const inputA = prompt("Enter your name?");

Use the alert() method for confirmation:

alert('Your name is ${inputA}');

Lastly, pass the object as the argument to print the output on the console

console.log(inputA);

Example 2: Get Multiple Values Using prompt() Method
In this particular example, declare an object with a name. Then, utilize the “prompt()” method, and pass the string as the parameter of this method:

var name = prompt("What's Your name?");

Define another object by following the same procedure:

var category = prompt("What is Your Category?");

Now, use the console.log() method and pass the argument “name” to add when user execute the code according to the below code block:

console.log(name + "!");

Pass the category as the argument to the “console.log()” to display on screen:

console.log(category + "?! I like this category");
console.log("Name is a " + typeof name);
console.log("Category is a " + typeof category);

Note: You can also get the input from the command line with the help of Node.js.

Conclusion

To get the user input from the command line with JavaScript, you can use the prompt() method that displays a dialog box that prompts the user for input. The “prompt()” method is utilized for returning the entered value if the user hits on “OK”. Furthermore, you can also get input with the help of Node.js. This post has stated the method for getting input from the command line with JavaScript.

About the author

Hafsa Javed