User Input

Program to take input from user using prompt()

BeginnerTopic: Basic Programs
Back

JavaScript User Input Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// 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.`);
Output
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:

Shows a message to the user
Waits for user input
Returns the entered value as a string
Returns null if user clicks Cancel

Important Notes:

prompt() only works in browsers (not Node.js)
All input from prompt() is returned as a string
You may need to convert to number using Number() 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:

More readable
Support multi-line strings
Allow embedded expressions

Converting Input Types:

let age = prompt("Enter age:");
age = Number(age); // Convert to number
age = parseInt(age); // Parse integer
// or

Node.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.

Table of Contents