Working with Data Stored in Variables
You can store and manipulate data in the computer's memory by creating variables. You assign data to variables using expressions.
A variable, as the name implies, can be changed. For example variables to keep count of wins and losses in a game or variables to hold login information.
To get some practice, this lesson's activities uses the console interactive mode.
Steps:
-
Open in the web browser the console.html file found in the completed folder.
Alternatively any open web page can be used.
-
Open the Console window in the web developer tools.
For details see the Using Web Browser Developer Tools to Learn lesson in the Getting Started section for interactively accessing the Chrome Console window.
1. Understanding Variables
Naming variables.
Variables have unique names. These are also called identifiers.
You create the names for variables. For example price
, firstName
, userName
, question10
or chapter_10
.
Rules and common practices for naming variables.
Rules for Naming Variables
-
Begins with a letter, a
$
or an_
. -
Uses letters, digits, underscores, and dollar signs. All others characters are not allowed such as spaces or hypens.
-
Letters in a name can be upper or lower case.
-
Case sensitive. For example variable names price, Price, pRiCe and PRICE are all different variables.
-
Variable names cannot use reserved words such as Javascript reserved words.
-
Can be a single character or longer. Although you can create quite long names, keep them short but meaningful.
Common practices for naming variables in Javascript.
-
If the variable starts with a word it is lower case. Example
price
versusPrice
. -
If the variable contains multiple words the all but the first word is capitalized. Example
unitPrice
oraverageMarketPrice
.
Declaring variables
Variables need to be declared using the var
keyword before you can assign data to them.
var firstName var lastName var unitPrice var quantity var amount var sold
More than one variable can be declared on a line using a comma ,
.
var firstName, lastName var unitPrice, quantity, amount, sold
Assigning values to variables.
You use the assignment operator =
to store data in a variable.
Warning: Often the assignment operator =
is easily mistaken for the equals to operator ==
.
The expression on the right of the the assignment operator is assigned to the variable on its left.
lastName = "Jones" amount = 1.25 * 100 sold = true
firstName = "Mary" city = "Hidden Gulch" state = "New Mexico" country = "United States" phoneNumber = "999-999-9999" income = 100000 expenses = 25000 likes = 100 liked = false onVacation = true
You can optionally assign the variable data when declared.
var firstName = "Mary", lastName = "Jones" var unitPrice, quantity unitPrice = 1.25 quantity = 100 var amount = unitPrice * quantity var sold sold = true
Reassigning data to variables
Variables can be reassigned.
lastName = "Jones" city = "Hidden Gulch" amount = 1.25 * 100 sold = true
lastName = "Smith" city = "Lost Mine" amount = 100 sold = false
amount = "Too Much" amount = 1000
sold = 100 sold = 'no'
Variable data types.
The undefined
data type.
A variable that has not been assigned a value has the data type undefined
.
var firstName
firstName != undefined
firstName == undefined
firstName = "Jonas";
firstName != undefined
firstName == undefined
Variables are dynamically assigned data types.
Variables have a data type such as undefined, string, number or boolean. In many languages you need to declare the data type of the variable before you use it. In Javascript you do not have to declare a variable’s data type.
Javascript assigns a variable a data type based on the data it represents. If the variable represents a string, then the data type of the variable is string. If you change the variable’s data to a number, then the data type of the variable changes to a number.
Variable Scope
Variables exist in a containment area called scope. The default scope is the global scope. Within any scope a variable can only be declared using the var
keyword once.
Later in the course, the notion of scope is revisited. At that time you learn that the same variable name can exist in multiple scopes but have different data.
2. Activity: Working with String Variables
-
Try using the following in the console window interactive mode.
firstName = "Mary"
lastName = "Jones"
fullName = firstName + lastName
fullName
fullName = firstName + ' ' + lastName
fullName
-
DIY: Use the variables from the last step to display the name as follows: …
Jones, Mary
… and store results in the fullName variable.
fullName = lastName + ', ' + firstName
fullName
3. Activity: Working with Number Variables
-
Try using the following in the console window interactive mode.
unitPrice = 1.25
quantity = 100
discount = .1
saleTotal = unitPrice * quantity * 1 - discount
saleTotal
Was the saleTotal variable correctly computed? Explain your answer.
No. The discount should be 12.5 based on 125, the unitPrice of 1.25 for a quantity of 100. This would give a saleTotal of 112.5.
The
unitPrice
, thequantity
and the number1
were multiplied resulting in 125. Then thediscount
was subtracted to arrive at 124.9.The correct saleTotal computation is to subtract the
discount
from the number1
first. This is accomplished by using the grouping operators for the addition.saleTotal = unitPrice * quantity * (1 - discount)
-
DIY: Create the following variables …
newValue = 1100
oldValue = 1000
… then compute the percent change from the oldValue to the newValue using the following formula …
newValue - oldValue / oldValue * 100
… and assign the solution to a variable named percentChange.
percentChange = (newValue - oldValue) / oldValue * 100
4. Activity: Working with Boolean Variables
-
Use the console window interactive mode to see if you have 50 dollars in cash needed to join a game of cards where largest allowed bill is a 20.
ones = 7
fives = 0
tens = 2
twenties = 1
ones + fives * 5 + tens * 10 + twenties * 20
ones + fives * 5 + tens * 10 + twenties * 20 > 50
-
Use the console window interactive mode to create the canPlay variable if you can plan and the minimumToPlay for the minimum balance to play.
minimumToPlay = 50
ones + fives * 5 + tens * 10 + twenties * 20 > minimumToPlay
canPlay = ones + fives * 5 + tens * 10 + twenties * 20 >= minimumToPlay
canPlay
-
Use the console window interactive mode to increase the cash on hand and reset the canPlay variable.
cashOnHand = ones + fives * 5 + tens * 10 + twenties * 20
cashOnHand
fives = 1
cashOnHand = ones + fives * 5 + tens * 10 + twenties * 20
cashOnHand
canPlay = cashOnHand >= minimumToPlay
canPlay