[Javascript] Ternary Conditionals

/**
    Ternary Conditionals
*/
//
//**Bad**
//
var isArthur = false;
var weapon;
if(isArthur){
    weapon = "Excalibur";
}else{
    weapon = "Longsword";
}
//
//**Good**
//
var weapon = isArthur ? "Excalibur" : "Longsword";
//
//**Be careful**
//
console.log("Current weapon: "+ isArthur ? "Excalibur" : "Longsword");//This will log out "Excalibur"
/*Why? we set isArthur = false;
  Because propriety level '+' > '?', and in Javascript only undefined, null, false, 0, NaN
  that we consider are false, other always evaluate as "truthy".
  So "String" ? "Excalibur" : "Longsword" --> "Excalibur"*/
//
//**To Fix**
//
console.log("Current weapon: "+ (isArthur ? "Excalibur" : "Longsword")); //--> "Longsword"

/**
    Compound ternary conditionals
*/
var isArthur = true;
var isKing = false;
console.log("Current weapon: "+ (isArthur && isKing ? "Excalibur" : "Longsword")); //--> "Longsword"

/**
    Ternaries can take action
*/
console.log(isArthur && isKing ? alert("Hail Arthur, King of the Britons!") :
                                 alert("Charge on, ye Knight, for the glory of the King!")); //--> "Charge on, ye Knight, for the glory of the King!"

/**
    Build and choose functions on the fly
*/
console.log(isArthur && isKing ? function(){
                                    alert("Hail Arthur, King of the Britons!");
                                }() :
                                function(){
                                    alert("Charge on, ye Knight, for the glory of the King!")
                                }());
//
//**Be careful**
//
/*
Remember that adding the parentheses calls the function expression!
*/

/**
Multiple actions in ternaries
*/
console.log(isArthur && isKing ? (weapon = "Excalibur" , helmet = "Goosewhite"):
                                 (weapon = "Longsword" , helmet = "Iron Helm"));
                                 
/**
Lastly, ternaries can be nested!
*/
var isArthur = true;
var isKing = false;
var isArcher = true;
var weapon;
var helmet;
isArthur && isKing ? (weapon = "Excalibur", helmet="Goosewhite")
                    :
                    isArcher ? (weapon = "Longbos", helmet="Mail Helm")
                             : (weapon = "Longsword" , helmet = "Iron Helm"); // --> weapon = "Longbos", helmet="Mail Helm"
//
//**NOTICE**: This is not easy to read! Don't do this!
//

 

posted @ 2014-08-11 03:45  Zhentiw  阅读(157)  评论(0编辑  收藏  举报