mardi 19 décembre 2017

Is it bad practice to use a function that changes stuff inside a condition, making the condition order-dependent?

var a = 1;
function myFunction() {
    ++a;
    return true;
}

// Alert pops up.
if (myFunction() && a === 2) {
    alert("Hello, world!")
}

// Alert does not pop up.
if (a === 3 && myFunction()) {
    alert("Hello, universe!")
}

http://ift.tt/2ou4XH0

myFunction increments a variable and returns something. If I use a function like that in an if statement that contains the variable which it increments, the condition would be order-dependent.

Is it good or bad practice to do this, and why?

Aucun commentaire:

Enregistrer un commentaire