ActionScript: Checking Equality or Comparing Values

by Gabriel Savimbi.

Share
|
Homepage | Submit your article | Contact | TOS
More articles on flash  

You are here: Categories » Computers and technology » Flash

You want to check if two values are equal.

Use the equality (or inequality) or strict equality (or strict inequality) operator to compare two values. To check whether a value is a valid number, use isNaN( ).

Equality expressions always return a Boolean value indicating whether the two values are equal. The equality (and inequality) operators come in both regular and strict flavors. The regular equality and inequality operators check whether the two expressions being compared can be resolved to the same value after converting them to the same datatype. For example, note that the string "6" and the number 6 are considered equal because the string "6" is converted to the number 6 before comparison:

trace(5 == 6);    // Displays: false
   trace(6 == 6);    // Displays: true
   trace(6 == "6");  // Displays: true
   trace(5 == "6");  // Displays: false

The logical inequality operator (!=) returns false if two values are equal and true if they are not equal. If necessary, the operands are converted to the same datatype before the comparison:

trace(5 != 6);    // Displays: true
   trace(6 != 6);    // Displays: false
   trace(6 != "6");  // Displays: false
   trace(5 != "6");  // Displays: true

On the other hand, the strict equality and inequality operators first check whether the values being compared are of the same datatype before performing the comparison. Differences in datatype cause the strict equality operator to return false and the strict inequality operator to return true:

trace(6 === 6);    // Displays: true
   trace(6 === "6");  // Displays: false
   trace(6 !== 6);    // Displays: false
 trace(6 !== "6");  // Displays: true

There is a big difference between the assignment operator (=) and the equality operator (==). If you use the assignment operator instead of the equality operator, you change the variable's value rather than testing its current value.

Using the wrong operator leads to unexpected results. In the following example, myVar equals 5 at first, so you might expect the subsequent if statement to always evaluate to false, preventing the trace( ) from being executed:

var myVar = 5;
   // The following code is wrong. It should be if (myVar == 6) instead
   if (myVar = 6) {
   trace("Rabbits are bunnies.");
   }
   trace("myVar is " + myVar);  // Displays: myVar is 6

However, the example mistakenly uses the assignment operator (=) instead of the equality operator (==). That is, the expression myVar = 6 sets myVar to 6 instead of testing whether myVar is 6. When used in an if clause, the expression myVar = 6 is treated as the number 6. Because any nonzero number used in a test expression converts to the Boolean true, the trace( ) action is called. Replace the test expression with myVar == 6 instead.

You can check an item's datatype using the typeof operator, as follows:

var myVar = 5;
   if (typeof myVar == "number") {
   trace("Yippee. It's a number.");
   }

But some numeric values are invalid. The following example results in myVar being set equal to NaN (a constant representing invalid numbers, short for "Not-a-Number") because the calculation cannot be performed in a meaningful way:

var myVar = 15 - "coffee";

Despite its name, NaN is a recognized value of the number datatype:

trace(typeof myVar);   // Displays: "number"

Therefore, to test if something is not only a number, but a valid number, you might try this:

var myVar = 15 - "coffee";
   if (typeof myVar == "number") {
   // Nice try, but this won't work.
   if (myVar != NaN) {
   trace("Yippee. It's a number.");
   }
 }

You can't simply compare a value to the constant NaN to check whether it is a valid number. Instead, you must use the special isNaN( ) function to perform the test.

To determine if a number is invalid, use the special isNaN( ) function, as follows:

var myVar = 15 - "coffee";
   if (isNaN(myVar)) {
   trace("Sorry, that is not a valid number.");
   }

To test the opposite of a condition (i.e., whether the condition is not true) use the logical NOT operator (!). For example, to check whether a variable contains a valid number, use !isNAN( ), as follows:

var myVar = 15 - "coffee";
   if (!isNaN(myVar)) {
   // The number is not invalid, so it must be a valid number.
   trace ("That is a valid number.");
   // This jumps to another frame, assuming you've labeled a frame "SuccessScreen".
   gotoAndStop ("SuccessScreen");
   }

Of course, you can perform comparisons using the well-known comparison operators. For example, you can use the > and < operators to check if one value is less than or greater than another value:

trace(5 < 6);    // Displays: true
   trace(5 > 5);    // Displays: false

Similarly, you can use the >= and <= operators to check if one value is less than or equal to, or greater than or equal to, another value:

trace(5 <= 6);   // Displays: true
   trace(5 >= 5);   // Displays: true

You should also be aware that ActionScript compares different datatypes differently. ActionScript data can be categorized into primitive datatypes (string, number, and Boolean) or composite datatypes (object, movieclip, and array). When you compare primitive datatypes, ActionScript compares them "by value." In this example, myVar and myOtherVar are considered equal because they both contain the value 6.

var myVar = 6;
   var myOtherVar = 6;
   trace (myVar == myOtherVar);         // Displays: true

However, when you compare composite datatypes, ActionScript compares them "by reference." Comparing items by reference means that the two items are considered equal only if both point to exactly the same object, not merely to objects with matching contents. For example, two arrays containing exactly the same values are not considered equal:

// Create two arrays with the same elements.
   arrayOne = new Array("a", "b", "c");
   arrayTwo = new Array("a", "b", "c");
   trace(arrayOne == arrayTwo);          // Displays: false

Two composite items are equal only if they both refer to the identical object, array, or movie clip. For example:

// Create a single array
   arrayOne = new Array("a", "b", "c");
   // Create another variable that references the same array.
   arrayOne = arrayTwo;
   trace(arrayOne == arrayTwo);          // Displays: true
Leave a comment or ask a question
Total comments: 0

Flash Disclaimer

  • The e-articles directory is not responsible for any and all copyright infringements by writers and authors. If you suspect the information contained by this page for any copyright infringements, please contact us to investigate the issue
ActionScript: Repeating an Operation Many Times - You want to perform a task multiple times within a single frame. Use a loop to perform the same task multiple times within a single frame. For example, you can use a for statement: (more...)
Avoiding Conflicting Variables in ActionScript - You want to make sure that variables within a function do not interfere with variables in other functions or within the timeline in which the function is defined. Use the var keyword to declare loc (more...)
How to Exit a Function in ActionScript - You want to exit a function. Functions terminate automatically after the last statement within the function executes. Use a return statement to exit a function before reaching its end. The (more...)
Move Clip Rotation - A property like _x and _y is the movie clip property _rotation. The _rotation property accepts a value in degrees. A circle is divided into 360 degrees. The values used by _rotation range f (more...)
Targeting Flash Movie Clips - The simplest way to target a movie clip is to use its name, followed by a dot, followed by the command you want to send. However, there are plenty of other ways to target a movie clip as we (more...)
Using Mathematical Operators in ActionScript - You want to modify something over time, such as the rotation or position of a movie clip. Use the compound assignment operators to change a variable or property in increments. Or, if increm (more...)
How to build an animated button using Flash - Time: 15 Minutes. Difficulty Level: Intermediate Requirements: Flash 8 Assumed Knowledge: Basic action (more...)
Enhancing Standalone Projector - You want to create an enhanced Standalone Projector with features such as borderless playback, custom titles, no Flash menus, and so on. Use a third-party tool such as SWF Studio or SWFKit to c (more...)
Creating Flash Buttons - Buttons are one of the three main types of symbols that you use in Flash. The others are movie clips and graphics. Making a New Button There are many ways to create a button. One (more...)
Bouncing Ball Script - Start a new Flash movie. Create a movie clip that has a ball graphic inside it. You can name the instance of the movie clip, myClip, but our code will not depend on the name of the clip. (more...)

 
free content
    Copyright © 2006 - 2012 e-articles.info.
The texts, articles and tutorials in the directory are property of their respective owners and authors.