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.
Practical Learning Notes for User Input
This JavaScript program is part of the "Basic Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.