DEV Community

Bilal Niaz
Bilal Niaz

Posted on

Interaction in Javascript

We have the ability to connect with the user and answer appropriately thanks to Javascript. It has a number of user-interface functions that aid interaction. Let's take a look at each one individually.

Alert:
Simply produces an alert box that may or may not contain the supplied content, but always includes a 'OK' button. It just displays a notice and stops the script from running until you press the 'OK' button. The modal window is the name for the pop-up mini-window.
alert('text');
Example:

// alert example
<script>
 alert('HI there'); // with specified content
 alert(); // without any specified content
</script>
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

It can be used for debugging or simply for popping something to the user.

Prompt:
Prompt is another user-interface function which normally contains two arguments.
prompt('text', default value);

The default value parameter is optional, albeit it functions as a placeholder inside a text field. The text is basically what you want to show the user, and the default value argument is what you want to display the user. It is the most commonly used interface since it allows you to ask the user for input and then use that information to build something.
Example:


<script>
// prompt example
let age = prompt('How old are you?', 50);// For default arg 
alert(`You are ${age} years old!`); 
</script>
Enter fullscreen mode Exit fullscreen mode

Output:

Image description
You can enter anything and it will print that, it doesn’t necessarily have to be a number. Without the default value, you have to enter something in the text-field otherwise it will print a blank space simply.

<script>
// prompt example
let age = prompt('How old are you?');

alert(`You are ${age} years old!`); 
</script>
Enter fullscreen mode Exit fullscreen mode

Image description

Confirm:
The confirm function basically outputs a modal window with a question and two button ‘OK’ and ‘CANCEL’.
confirm('question');
Example:

<script>
// confirm example 
let isHappy  = confirm('Are you Happy?');
alert(`You are ${isHappy}`); 
</script>
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

It will print true or false based on your choice of clicking the ‘OK’ button or ‘CANCEL’ button respectively.

Top comments (0)