Search code examples
javascriptif-statementboolean-operations

JavaScript if else statement ignored


I have a simple if statement below:

function calculateTotal() {

    if (tanksize != 1 || tanksize != 2) {
        var setupPrice = basicPrice + StatPrice() + DigiStatPrice() + IRPrice() + UVPrice() + cagePrice();
        var setupPrice2 = toFixed(setupPrice, 2);

    } else {
        var setupPrice = basicPrice;
        var setupPrice2 = toFixed(setupPrice, 2);
    }


    //display the result at the top of page
    var divobj = document.getElementById('totalPrice');
    divobj.innerHTML = "£" + setupPrice2;

    //display the result at the bottom of page
    var divobj = document.getElementById('totalPrice2');
    divobj.innerHTML = "£" + setupPrice2;
}

But when the tanksize variable is set to 1 or 2, the setupPrice variable is still calculated by adding the basicPrice + StatPrice...etc.


Solution

  • You need to use:

    if (tanksize !== 1 && tanksize !== 2) {
    

    with the && operator, or

    if (!(tanksize ===1 || tanksize === 2)) {
    

    In your code, you have the first block executing any time the value is not 1 or is not 2, which equates to it always executing.

    If the value is 1, then tanksize != 2 is true so tanksize!=1 || tanksize!=2 is true.

    If the value is 2, then tanksize != 1 is true so tanksize!=1 || tanksize!=2 is true.

    In other words, tanksize!=1 || tanksize!=2 is always true, no matter what the value of tanksize is.