Header Ads

Check whether a person can Drive or not using Ternary Operator

Algorithm to check whether a person can drive or not using a ternary operator:

Prompt the user to enter their age.
Assign the input to a variable called age.
Using a ternary operator, check if the age is greater than or equal to 18.
If the age is greater than or equal to 18, assign the message "You can drive" to a variable called message.
If the age is less than 18, assign the message "You can't drive" to the message.
Print the value of the message to the console.


Code :

let age = prompt("What is your age?");
let a = age>18 ? "You can drive":"You can't drive";
console.log(a);

Output :

What is your age?> 19
You can drive


Explanation :



The code let age = prompt("What is your age?"); prompts the user to input their age and stores the result in a variable called age. The prompt() function displays a dialog box with the specified message and waits for the user to enter a value. The entered value is then assigned to the variable age.

In the second line, let a = age > 18 ? "You can drive" : "You can't drive"; uses a ternary operator to check whether the value of age is greater than 18. If the age is greater than 18, the value of the a variable is set to "You can drive". Otherwise, the value of a is set to "You can't drive".

Finally, the code console.log(a); logs the value of the a variable to the console. This means that the result of the ternary operation is printed to the console, which will either be "You can drive" or "You can't drive" depending on the value of age.




Related Articles :












Post a Comment

0 Comments