Search code examples
javascriptif-statementconfirm

How to use multiple Javascript statement conditions with an "OR" confirm


I have the following function containing a condition in javascript.

function dosomething(id, action) {
    if (action != 'delete' || confirm("Are you sure?")) {
         alert('if action equals delete, then it has been confirmed'); 
         // long lines of code executed here. 
    }
} 

In the above function condtion, it checks if action is NOT equal to "delete". If its equal delete, it gives a confirmation before proceeding. But I'd like to add another value as well as "delete", where the "Are you sure?" message shows/needs confirmation.

I am unable to do this and I've tried the following.

if ((action != 'delete' || action != 'report') || confirm("Are you sure?")) { ...

What I am trying to do is, if the action == delete or report, the confirmation message should pop-up.

I don't want to write two different if statements (as shown below), as there is a lot of code that needs to execute after confirmation, and it will be bad practice.

if (action != 'delete' || confirm("Are you sure?")) {

THEN

if (action != 'report' || confirm("Are you sure?")) {

THANKS


Solution

  • It would probably be clearer to do something like this, reducing indentation and the need for careful reading of the boolean logic:

    function dosomething(id, action) {
      if (action === 'delete' || action === 'report') {
        if (!confirm("Are you sure?")) return;
      }
      // long lines of code executed here.
    }
    

    It would be possible to write it all in one check like

    if ((action === 'delete' || action === 'report') && !confirm("Are you sure?")) return;
    

    but that's less readable IMO.