Deeper Look: Defining Variables
Now that we know what variables are, it's time to look deeper into their structure and how to play with them. Also, we will learn about a new error type we can now check to avoid: Error 1120.
Declaring and assigning variables is not new to us. We have discussed variables in almost every other video. However, we didn't dig very deeply before, stating it would be discussed later. Now it's the time to know everything about variables and look more deeply into them.
First of all, to declare a variable we need the keyword var. For example, var a; Here, 'a' is the variable. Earlier we have seen variables declared along with their data types. But here we can't figure out what type of data the variable is going to store. In the same way, Flash also can't understand the data type that is going to be used. In this case, if we assign a string to the variable a, Flash takes the data as string. In the next line, if we again assign a value to 'a' of data type Number, Flash doesn't show any error but takes the integer value as well.
Here we need to understand one thing :i Flash generates an error only if the assigned data type doesn't match the defined data type of the variable. Above, we didn't define any type for a. Ergo we recommend defining the data type during the declaration of the variable: var a:int; will do it. Now, if you happen to forget a is an integer and write a="uh oh this is a string!"; Flash will puke! Assigning a type to a variable at definition will make the application run smoothly and it helps us as well while writing the code. You must declare a variable along with its data type and assign the same type of data to it.
Single Command in Single Line
The next thing regarding variable definitions is the necessity to end the declaration with a semicolon. The application considers a line to be ended only if the semicolon is present. If there is no semicolon, Flash considers the next line as part of the first line's code – until that semicolon is reached! Think this could cause an issue of two? A bunch of errors will appear. But if you want to use the same command for declaring two different variables (a:String b:Number;) then the semicolon should be specified at the end of the second statement. These two statements can be written either on one or two lines. Flash considers it to be a single line until the semicolon is reached. Although ActionScript is a forgiving language and many times will automatically end the line on its own, it's good practice to always end a line with a semicolon as other languages aren't as forgiving.
Ready to Level Up Your Skills?
Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!
Enroll Now for Free!