Ternary expressions


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. var myVar = 1,
  2. newVar;
  3.  
  4. /**
  5.  * Standard if else statement
  6.  */
  7. if (myVar === 1) {
  8. newVar = 'One';
  9. } else {
  10. newVar = 'Anything else';
  11. }
  12.  
  13. alert(newVar); //One
  14.  
  15. /**
  16.  * Same as this standard ternary expression
  17.  */
  18. newVar = (myVar === 1) ? 'One' : 'Anything else';
  19.  
  20. alert(newVar); //One
  21.  
  22. myVar = 2;
  23.  
  24. /**
  25.  * Embedded if statement
  26.  */
  27. if (myVar) {
  28.  
  29. if (myVar === 1) {
  30. newVar = 'One';
  31. } else {
  32. newVar = 'Two';
  33. }
  34.  
  35. } else {
  36. newVar = 'Anything else';
  37. }
  38.  
  39. alert(newVar); //Two
  40.  
  41. /**
  42.  * Same as this ternary expression
  43.  */
  44. newVar = (myVar) ? ((myVar == 1) ? 'One' : 'Two' ) : 'Anything else';
  45.  
  46. alert(newVar); //Two
  47.  
  48. myVar = 'Foo Bar';
  49.  
  50. /**
  51.  * If Then Else If statement
  52.  */
  53. if (myVar === 1) {
  54. newVar = 'One';
  55. } else if (myVar === 2) {
  56. newVar = 'Two';
  57. } else {
  58. newVar = 'Anything else';
  59. }
  60.  
  61. alert(newVar); //Anything else
  62.  
  63. /**
  64.  * Same as this ternary expression
  65.  */
  66. newVar = (myVar == 1) ? 'One' : (myVar == 2) ? 'Two' : 'Anything else' ;
  67.  
  68. alert(newVar); //Anything else

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.