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:
Use the alert() method for confirmation:
Lastly, pass the object as the argument to print the output on the console
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:
Define another object by following the same procedure:
Now, use the console.log() method and pass the argument “name” to add when user execute the code according to the below code block:
Pass the category as the argument to the “console.log()” to display on screen:
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.