When to use the ?: conditional operator


/ Published in: ActionScript 3
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*Fumio Nonaka in: Coding|Jump To Comments February 9, 2011
  2. The conditional operator ?: is used to select an alternative value to be assigned. It is basically faster than the if statement.*/
  3.  
  4.  
  5. myVariable = (condition) ? valueA : valueB;
  6.  
  7. view plaincopy to clipboardprint?
  8. if (condition) {
  9. myVariable = valueA;
  10. } else {
  11. myVariable = valueB;
  12. }
  13. /*However if the value selected by the conditional operator is to be added with the addition assignment operator +=, its operation will come to be slow.*/
  14.  
  15.  
  16. myVariable += (condition) ? valueA : valueB;
  17. //Using the assignment operator instead makes it a little faster.
  18.  
  19.  
  20. myVariable = (condition) ? myVariable + valueA : myVariable + valueB;
  21. //But in this case, the if statement is better to use.
  22.  
  23.  
  24. view plaincopy to clipboardprint?
  25. if (condition) {
  26. myVariable += valueA;
  27. } else {
  28. myVariable += valueB;
  29. }

URL: http://blog.jactionscripters.com/2011/02/09/when-to-use-the-conditional-operator/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.