We’ve already seen variables in a few of the examples from before; anytime we typed in the keyword
var followed by a symbolic name, such as
Declaring and Assigning a Variable
When we declare a variable we follow this syntax:
var toast. Try typing this into your console. This statement,
var toast is telling the compiler that the word
toast, is going to be used as a label to refer to data (note: an empty or unassigned variable always has a value of
To assign data to a variable we use the equal sign
= like this,
toast = 10; and now the variable
toast refers to the number
10. If we type in the variable name
toast in the compiler now, it should return the number
10. We can also reassign the variable
toast to another piece of data like the string
"burnt" by simply inputting,
toast = "burnt"; into the console. Now, the variable toast will no longer refer to the number 10 but it will instead refer to
var is mutable.
Rules for Variables
var a, b, c, d, e, f;. We can declare and assign variables on the same line:
var z = 10; and declare and assign multiple variables on the same line
var firstName = "john", lastName = "doe", age = 27;. We can use this last example to easily organize a sentence string:
firstName + " " + lastName " is " + age " " years old!" which will output
"john doe is 27 years old!" in our console.
var x = 12 + 10; will give us the value
22 as the variable
x. You may also concatenate strings, use division, multiplication, or subtraction while assigning a variable.
x will have a value of
FirstName is different from the variable
firstName and the variable
A is different from
Special Characters and Naming
firstName variable as
first_name and they would be perfectly acceptable.
In programming in general, there is a specific naming philosophy called camel case. In camel case you use a lowercase letter for the first word in the variable and an uppercase letter for every word there after.
lastName follow the camel case naming convention.
coolBlackCat is another example of this camel case convention. Pick which ever naming convention you prefer but keep things consistent, if you plan to use camel case in your program then don’t change to underscores or dashes in the middle.