Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Introducing JavaScript Your First JavaScript Program

Difference between alert() and confirm()

In somewhere i saw using confirm() to present a popup massage to user for confirmation. I'm little bit confused, what's difference between alert() and confirm() ?

2 Answers

Hi Nazmul

I think when you are using alert, it give the user a popup display with a message and 'OK' option.

When you using confirm is use when there is a need for the user to verify with an OK or Cancel (true or false). Confirm can also re-written 'Yes' or 'No" and whichever the users click can be program for different outcomes.

One thing about using confirm, I think is that it forces the browser to read the message and prevents the user from accessing any part of the page until the user closes the confirm box.

Martin Imfeld
Martin Imfeld
5,403 Points

alert() displays a dialog with only one button (in most browsers the button says 'ok'). confirm() displays a dialog with two buttons: 'ok' and 'cancel' ... the nifty thing is, that confirm will return what the user selected. Try the following

var result = confirm("Do you want a cone of ice-cream?"); if(result == true) { document.write("Here, strawberry and vanilla. Enjoy!"); } else { document.write("Well, i'll give it to someone else then."); }

The first lines gets the answer from the user. It is stored in a variable (a container for information) as a true or false value. If the user selected 'ok' result will contain 'true', if the user selected 'cancel' result will contain 'false'.

The other lines are easy to understand (it is almost English) ... I am sure we are going to learn about if and else later on :)