User Input

Program to take input from user using prompt()

JavaScriptBeginner
JavaScript
// 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.

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:

    javascript
    "Hello, " + name + "!"
    
  2. Using template literals (ES6):

    javascript
    `Hello, ${name}!`
    

Template literals are preferred because they're:

  • More readable
  • Support multi-line strings
  • Allow embedded expressions

Converting Input Types:

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

Node.js Alternative:

In Node.js, use readline module or readline-sync package for user input.