Variables and ExpressionsA variable is a container that holds a piece of data (called the value ). An expression is the part of a JavaScript statement that evaluates the variable, substituting the value for the variable where necessary. In JavaScript, we use the keyword var to create a variable, and the equal sign ( = ) to assign a value to a variable. Here is a typical group of statements using variables: var x = 6; var y = 3; var z = x + y; x = x + 1; y = y + 1; var a = x + y; At the end of this group of statements, the variable z is equal to (contains) 9; a is equal to 11. A variable can contain different types of information, including numbers , pieces of text called strings , and true/false values called Booleans . Depending on the kind of information contained in a variable, the JavaScript interpreter evaluates the expression containing it differently. When variables contain numbers, for instance, as in the preceding example, the + operator means to perform a mathematical addition operation. When variables contain text strings, the + operator means to join the two strings together, as follows : var a = "inter"; var b = "mediate"; var c = a + b; At the end of this group of statements, the variable c is equal to the text string "intermediate." This process of joining text strings is called concatenation . Variables can be concatenated with each other and with other text strings, like this: var d = "Fred"; var e = "Barney"; var f = d + " and " + e; At the end of this group of statements, the variable f is equal to the text string " Fred and Barney ". The word and , as well as the spaces on either side of this word, are contained in the text string that is joined to, or concatenated with, the two variables. Practice Session #2In this exercise, you'll build on the practice file you created in the previous exercise, using variables to construct the message that appears in the alert window.
|