📅 November 7, 2017
A variable allows us to store a value that can change during a script’s execution.
Its contents are variable — meaning it can change, and that is why it is called a variable.
Variables exist in memory, and we lose their contents when a computer is powered off or after the script is finished using it (often encountered during a concept called scope).
The Apple Stand Example
Suppose we are running an apple stand located along a busy highway in a popular tourist trap. To keep track of how many apples we have at any given moment in our apple stand, we have computerized the process with a script that records the number of apples stocked and sold.
This script needs a way to store how many apples are present in the inventory, so we use a variable named apples that stores the number of apples currently in the apple stand.
As tourists purchase apples, the value of the variable decreases with a new value, and as the fruit truck arrives and replenishes the stand’s apple supply, the value of the variable increases. Either way, the number of apples recorded in the apples variable is changing.
Declaring and Defining Variables
var is the keyword, and apples is the identifier.
By default, variables are undefined and have no value. We can test this by running this script to see a variable’s content in the Browser’s console output (Shift + Ctrl + I in the Vivaldi browser).
We see that the console.log() output in line 13 has an undefined state.
Defining assigns a value to a variable, and we use the assignment operator, represented by the equals character (=), to store a value in the variable.
apples = 100;
Note that the variable must first exist before we can assign anything to it.
We can place the declaration and definition in a single statement.
var apples = 100;
Both techniques work, so which to use depends upon the needs of the script.
Now, if we run the script, we will see the value of apples in the console output.
We only declare a variable once. After that, we can use its identifier (name) to access the variable.
Do not do this:
Instead, do this:
Same result, but apples is declared once. Simply use the identifier to store new values in the variable.
Is var required?
Suppose apples does not exist when we assign the value 8 to it.
Avoid this practice since it can lead to confusion later in larger scripts. Use the var keyword:
var apples = 8;
Variable Naming Rules
We cannot name a variable anything we want. There are rules to follow that prevent syntax errors and ambiguities.
1. Identifiers are case-sensitive. apples and Apples are two different identifiers.
2. The identifier must begin with a letter, the dollar sign ($), or the underscore (_). It cannot begin with a number.
$apples _apples apples_sold apples_rotten
3. The identifier may contain any combination of letters, numbers, dollar signs ($), and underscores (_). Do not use spaces, hyphens (-), or periods (.).
$apples23 apples_today2017 apples_$lastyear apples_ROTTEN___20
var var = 3; // No, no.
Camel Case Notation
Suppose you want to have multiple words in an identifier. Spaces are not allowed, so is this possible?
Yes. Capitalize each word. By convention (things most programmers have agreed upon as good practice), identifiers begin as lowercase, and successive words begin with capital letters. For example,
applesDeliveredToday applesReturned applesThrownAwayDueToWorms applesHistory2010_2015 applesHistory2016_2018
The combination of lower and uppercase resembles humps on a camel’s back.
If you dislike the “humpy” capitalization, underscores will achieve the same result.
apples_delivered_today apples_returned apples_thrown_away_due_to_worms apples_history_2010_2015 apples_history_2016_2018
Use whichever method you prefer, but be consistent throughout your script for readability. Remember, spaces are not allowed in an identifier because whitespace denotes its end.
Note: Avoid capitalizing identifiers. A capitalized identifier usually denotes a class in other programming languages. Use apples, not Apples for a variable’s identifier.
The equals character (=) is called the assignment operator. It says, “Take whatever value is on the right of the = character and store it in the variable.” It does not mean that two expressions are equal in value.
A data type specifies the kind of data being worked with. Here are a few generic examples:
- Integer: -5, 0, 5, 3, -1000
- Floating-point: 5.73, 3.141592, -33.0009, 1.00009
- Boolean: true, false
- Numeric: Any signed or unsigned number with or without a decimal point.
- String: Text, such as “Hello, World!”
- Boolean: true or false values.
Other data types exist. For example, undefined is also a data type, and it is the data type returned for a variable that does not yet contain an assigned value.
Strong vs. Loose
Other languages, such as C and Java, are strongly typed. Strong typing means that you must specify the exact type of data that a variable will hold when the variable is declared, and the variable can hold only that type and no other. Any attempt to assign a different data type to a variable will result in an error.
For example, in Java, suppose we declare an integer variable that holds the value 100.
int number = 100;
Let’s assign a different value to the number variable.
number = 200;
So far, so good. This is because the variable number holds integers, and 100 and 200 are both integers.
But suppose we try to assign a floating-point value (a number containing a decimal point) to the number variable.
number = 300.34567;
This will not work, and Java will complain and refuse to compile. The variable number cannot store a floating-point value because it was declared as an integer variable.
var number = 100; number = 200; number = 300.34567;
In fact, we can even assign a string to the number variable.
number = "Hello, World!";
The Boolean Data Type
What good is Boolean? Why not use 0 and 1 instead?
Programming constructs often require a variable that holds one of only two possible states.
- On or off.
- Yes or no.
- 0 or 1.
- Up or down.
- Left or right.
Boolean is named after the English mathematician, George Boole, who formalized the laws of Boolean algebra around 1854. A Boolean data type holds a true or false value named…wait for it…true or false. Yes, these are keywords, so you cannot name an identifier true or false.
true and false are case-sensitive with lowercase true and lowercase false. Do not use True or False since these will return errors.
Multiple Variable Declarations
We can declare more than one variable in a single statement using one var keyword.
Suppose we have four variables to declare for our apple stand. We could write,
var apples = 10; var applesSold; var applesReturned = 0; var applesStocked;
This is perfectly valid code. Nothing wrong with that. But we could also do this on one line:
var apples = 10, applesSold, applesReturned = 0, applesStocked;
Both are equally valid. A comma separates each identifier, and assignments are also allowed. Which method you use best depends upon which facilitates readability.
Boolean Variable Example
Whatever string is passed to the confirm() method will be displayed in the popup to give instructions to the user. The user must click on either the OK button or the Cancel button, and a Boolean value will be returned depending upon which button was clicked.
- OK = true
- Cancel = false
The return value is stored in the variable choice, which is displayed in the console.