User Input
Program to take input from user using prompt()
JavaScript User Input Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Getting user input using prompt()
let name = prompt("Enter your name:");
let age = prompt("Enter your age:");
console.log("Hello, " + name + "! You are " + age + " years old.");
// Using template literals (modern approach)
console.log(`Hello, ${name}! You are ${age} years old.`);Enter your name: Alice Enter your age: 25 Hello, Alice! You are 25 years old. Hello, Alice! You are 25 years old.
Understanding User Input
This program demonstrates how to get user input in JavaScript. There are different methods depending on the environment.
prompt() Method
The prompt() function displays a dialog box asking the user for input:
null if user clicks CancelImportant Notes:
prompt() only works in browsers (not Node.js)prompt() is returned as a stringNumber() or parseInt()String Concatenation
Two ways to combine strings:
1.
Using + operator:
"Hello, " + name + "!"
2.
Using template literals (ES6):
`Hello, ${name}!`
Template literals are preferred because they're:
Converting Input Types:
let age = prompt("Enter age:");
age = Number(age); // Convert to number
age = parseInt(age); // Parse integer
// orNode.js Alternative:
In Node.js, use readline module or readline-sync package for user input.
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.