The best way to understand variables better is to actually create some.
To create a local variable we use the reserved word "var" followed by the name of the variable we are creating.
This statement has defined a local variable and given it the variable name apples. Note that the word var must be in all lowercase and the variable that we have just created is a different variable from Apples or APPLES.
If we actually want to assign an initial value to a variable, we need to specify the value that we want to assign. Here are a few examples of how to do this.
1 var male = true;
2 var bedrooms = 3;
3 var myName = "Stephen";
Each of these examples creates a variable that holds a value with a different type.
1 creates a Boolean variable named male. A Boolean variable can contain one of two values – true and false. Boolean variables are extremely useful when it comes to making comparisons between two values since the result of the comparison will be a Boolean variable.2 creates a variable that contains a number – in this case the initial value of that number is 3.
4 '"Beware" he said'
6 ' He\'s "zonked"'
2 and 3 show how if we include a reserved word such as true or a number inside quotes or apostrophes then we have a text string rather than a Boolean or a number. They have the same apparent value but a different data type. In fact “false” evaluates to the Boolean value true.
4 shows a text string contained within apostrophes that contains quotes within the content of the string itself 5 shows the reverse of this, a text string that is contained within quotes and consists of a single apostrophe. The easiest way of including either quotes or apostrophes in a text string is to use the other one as the string delimiter (to mark where the text starts and finishes).
Finally, 7 shows how we escape the escape character so as to restore its meaning as a backslash character. This also illustrates a common trap that people fall into when coding Windows style path references into their script as they forget to escape the backslash characters.
This article written by Stephen Chapman, Felgall Pty Ltd.