Loading...

Conditional Statements

Conditional Statements

Conditional Statements test a claim and then either run a block of code or pass to the next step. Ultimately, these statements provide dynamic programmed responses where data can be set programmatically or change, like in the case of user input, and the JavaScript code can respond in different programmed ways.

Conditional Statements:
  • if - When a condition is met, run a block of code.
  • else - When a condition is not met in an if statement, run a different block of code.
  • else if - When a condition is not met in an if statement, check if another condition is met. If so, run a block of code
  • ternary operator - Allows for if-else statements to be written in a more simple form.
  • switch - This will check if a condition is met on a series of options ( 'cases') and then performs specific code if a match is made.

↓ Examples ↓

let aPerson = 'R2D2';

if (aPerson === 'R2D2') {
    console.log('Success!', aPerson)
} else if (aPerson === 'C3PO') {
    console.log('Success!', aPerson)
} else {
    console.log('This is not the droid we are looking for.')
}

//    RESULT: Success! R2D2


//    Change the variable and run again
aPerson = 'C3PO';

if (aPerson === 'R2D2') {
    console.log('Success!', aPerson)
} else if (aPerson === 'C3PO') {
    console.log('Success!', aPerson)
} else {
    console.log('This is not the droid we are looking for.')
}

//    RESULT: Success! C3PO


//    Change it again...
aPerson = 'IG88';
if (aPerson === 'R2D2') {
    console.log('Success!', aPerson)
} else if (aPerson === 'C3PO') {
    console.log('Success!', aPerson)
} else {
    console.log('Fail.', aPerson, ' is not the droid we are looking for.')
}

//    RESULT: Fail. IG88 is not the droid we are looking for.


//    Ternary operator
//    condition ? option1 : option2

//    This function will be used in the ternary example below
function isUserValid(bool) {
    return bool;
}

//    Below is a function written without a ternary operator
function condition() {
    if (isUserValid(true)) {
            return "You may enter"
        } else {
            return "Access denied";
        }
    }
condition(true); // RESULT: "You may enter"


    //    Here it is with the ternary operator
    //    This is much shorter, but does accomplish the same thing
    let answer = isUserValid(true) ? 'You may enter' : 'Access denied';

    console.log(answer) //    RESULT: "You may enter"


// Lets try a switch function
const choice = 'R2D2';
switch (choice) {
 case 'Bobba Fett':
    console.log('Case 1:', choice);
    break;
 case 'R2D2':
    console.log('Case 2:', choice);
    break;
 case 'C3PO':
    console.log('Case 3:', choice);
    break;
 default:
    console.log('It looks like' + choice + ' is not here.');
}
// Result: Case 2: R2D2

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top