Not much in today's post. I was checking my web stats last night, and the search terms "actionscript testing for even number" showed up in the top ten searches from Google. I haven't posted on this, so I don't know how I got these search terms in my logs ( I once got "deep frying turkeys"), but as a service to whoever was looking for that, here you go:

  1. // testing for an even number - if/else
  2. var myNum:Number = 6;
  3. //
  4. if ((myNum % 2) == 0) {
  5.         trace ("it's even");
  6. } else {
  7.         trace ("it's odd");
  8. }

Or, you can condense the if/else blocks into one line using a ternary operator.

  1. // testing for an even number - ternary operator
  2. var myNum:Number = 6;
  3. //
  4. ((myNum % 2) == 0) ? trace ("it's even") : trace ("it's odd");

Just copy and paste the code above to try it out, replacing myNum with any number. The trick here is the modulo operator (%). It returns the remainder of the first item divided by the second. If there is no remainder when your first number is divided by two, then you have an even number.

The modulo is actually pretty handy. It can be used in the situation above, when trying to find an even number, but I've also used it in a music application to build a metronome and determine the different beats of a measure.

This is old news to a lot of developers out there, but sometimes it's nice to throw something out there for the n00bs as well. We all were once.