In this tutorial we’re going to learn how to use Prompt function using JavaScript.
let age = prompt("What is your age?", 18);
– This line of code uses theprompt()
function to prompt the user for their age. The second argument, 18, is the default age if the user does not enter anything.let welcome = (age < 18) ? () => alert('Hello!') : () => alert("Greetings!");
– This line of code creates a variable calledwelcome
and assigns it an anonymous function. The anonymous function takes one argument,age
, and returns a function that displays a message. Theage < 18
expression inside the?
ternary operator checks if the user’s age is less than 18. If it is, the first function is returned. Otherwise, the second function is returned.welcome();
– This line of code calls thewelcome()
function. This function will display the message “Hello!” if the user’s age is less than 18, or the message “Greetings!” if the user’s age is 18 or older.
Just use below code and put put inside the script tag
let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
() => alert('Hello!') :
() => alert("Greetings!");
welcome();
Output:-
I hope its helpful for you 👍