• Search form is empty!

  • 010 TypeScript - ternary operator

    http://robertdunaway.github.io

    TypeScript code kata list

    All code kata lists

    Smiley face

    010 TypeScript - ternary operator

    Duration

    5 minutes

    Brief

    Using a ternary operator (?) to check for null.

    For more information

    BING/GOOGLE: “TypeScript ternary operator ?”

    Instructions

    Get tutorial folder or the entire katas-typescript repo.
    Open the [before/*.sln] file and execute the kata.
    Feel free to execute this kata multiple times because repetition creates motor memory.

    Github

    Kata

    Recreate the logic below with the ternary operator (?). The ternary operator can be used to look for null but what it’s really doing is creating conditional logic based on a true/false response. If null then false is returned.


    
        var myVal: number = null;
        var result: number = null;
    
        // using an if statement
        if (myVal == null) {
            result = 0;
        }
        else {
            result = myVal;
        }
    
    


    Now change the “myVal” variable to equal 5 and execute operation again. Result is now set equal to “myVal” because “myVal” is not null.


    
        // Using a ternary operator to check for null.
        result = myVal ? myVal : 0;
        console.log('result = myVal ? myVal : 0; // result = ' + result);
    
        myVal = 5;
        result = myVal ? myVal : 0;
        console.log('result = myVal ? myVal : 0; // result = ' + result);
    
    


    Create logic that checks if two values are equal. At this point in the exercise result and myVal should both be 5 so a ternary operator will return true for (myVal = return).


    
        // Using a ternary operator to evaluate.
        result = (myVal == result) ? 'myVal and result both equal ' + result : 'values are not equal';
        console.log(result);
    
    


    Smiley face


    Next

    Take a few minutes and imagine more examples.

    Smiley face

    0 comments:

    Post a Comment