JS - if else and else if statement

weixin_43012796發表於2020-12-10
// 1 equal or not
// 3 == 3 == "3" true
// 3 === "3" false
function compareEquality(a, b) {
    if (a == b) {
        return "Yes";
    }
    return "No";
}

console.log(compareEquality(10, "10")); // string convert to number

function compareEquality2(a, b) {
    if (a === b) {
        return "Yes";
    }
    return "No";
}

console.log(compareEquality2(10, "10")); // no string convert to number

function compareNotEquality(a, b) {
    if (a !== b) {
        return "Yes";
    }
    return "No";
}

console.log(compareNotEquality(10, "10")); // strict not equal

// 2 if clause
function testGreaterThan(val) {
    if (val > 100) {
        return "Over 100";
    }
    if (val > 10) {
        return "Over 10";
    }
    return "10 or Under";
}

console.log(testGreaterThan(10));

// 3 doubleif clause
function testDoubleIf(val) {
    if (val > 100) {
        if (val < 200)
        return "Over 100 and less than 200";
    }
    return "100 or Under and 200 or higher";
}

console.log(testDoubleIf(190));

// simpler version
function testDoubleIf2(val) {
    if (val > 100 && val < 200) {
        return "Over 100 and less than 200";
    }
    return "100 or Under and 200 or higher";
}

console.log(testDoubleIf2(190));

function testDoubleIf3(val) {
    if (val <= 100 || val >= 200) {
        return "Outside";
    }
    return "inside";
}

console.log(testDoubleIf3(190));

// 4 if else
function testIfElse(val) {
    if (val <= 100) {
        return "Inside";
    }
    if (val > 100) {
        return "Outside";
    }
}
console.log(testIfElse(190));
// simpler
function testIfElse2(val) {
    if (val <= 100) {
        return "Inside";
    }
    else {
        return "Outside";
    }
}
console.log(testIfElse2(290));

// 5 else if
function testElseIf(val) {
    if (val <= 100) {
        return "Inside";
    }
    else if (val <= 200) {
        return "Middle";
    } else {
        return "Outside";
    }
}
console.log(testElseIf(190));

相關文章