Console Input Javascript

Taking input from the console in JavaScript depends on your environment:

1. In a Browser:

1.1 Prompt

let name = prompt("Please enter your name:");
console.log("Hello, " + name + "!"); 

1.2 HTML Input Element

If you want to take input from an HTML form, you can use input elements in your HTML and retrieve the value using JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Example</title>
</head>
<body>
    <input type="text" id="userInput" placeholder="Enter something" />
    <button onclick="getInput()">Submit</button>

    <script>
        function getInput() {
            const input = document.getElementById('userInput').value;
            console.log(input);
        }
    </script>
</body>
</html>

2. In Node.js:

2.1 Readline

const readline = require('readline');
const rl = readline.createInterface(
	{
		input: process.stdin,
		output: process.stdout
	}
);

rl.question('What is your name? ', (name) => {
	console.log(`Hello, ${name}!`);
    rl.close();
  }
);

2.2 Prompt Sync

const prompt = require('prompt-sync')();
const name = prompt('What is your name? ');
console.log(`Hello, ${name}!`);