0

Javascript is throwing an exception if I attempt to use a break; statement inside an if else. so I'm using this code in Salesforce Classic Button Javascript

I have multiple if/else conditions.

if (condition1...) {
    //do stuffs
else {
    //show message 1
}

if (condition2...) {
    //do stuffs
else {
    //show message 2
}

How do I overcome this? I tried to use break or return I get the unexpected exception.

PROBLEM: I'm getting both messages from condition 1 and condition 2

1 Answer 1

0

So first, as a best practice try to avoid multiple return statement and break keyword, it makes the code more difficult to understand and is error prone.

Secondly if I understand, when message 1 is shown, you don't want to show message 2. Depending on how stuff 1 and stuff 2 needs to be executed you can use one of the two approach:

First

stuff 2 can be done only if stuff 1 is also done

if (condition1) {
  // do stuff 1

  if (condition2) {
    // do stuff 2
  } else {
    // show message 2
  }
} else {
  // show message 1
}

Second

stuff 2 can be done whether or not stuff 1 is also done

let displayMessage = false

if (condition1) {
  // do stuff 1
} else {
  displayMessage = true
  // show message 1
}

if (condition2) {
    // do stuff 2
} else if (!displayMessage) {
    // show message 2
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .