Let’s Learn JavaScript • Lesson 7 • Variables

📅 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

Declaring a variable brings it into existence so the program can use it. In JavaScript, we declare a variable using the var keyword followed by the name of the variable, called an identifier.

var apples;

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).

A variable without a value returns undefined.

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.

Console shows 100 apples in the apples stand.

We only declare a variable once. After that, we can use its identifier (name) to access the variable.

Do not do this:

Redeclaring the same variable repeatedly.

While JavaScript will execute the code without errors, the added use of var in each statement is unnecessary. Why do the extra typing?

Instead, do this:

Much better. Declare once, use again.

Same result, but apples is declared once. Simply use the identifier to store new values in the variable.

Is var required?

Technically, no. While other languages might throw a fit over improper variable declarations, JavaScript allows sloppy coding practices. JavaScript will still create a variable in absence of the var keyword. However, it is good programming practice to use var when declaring a variable in order to be specific about the declaration and to make it clear in your code where the variable is created.

If a variable does not exist when you try to assign a value to it, then JavaScript will automatically create the variable at that point.

Suppose apples does not exist when we assign the value 8 to it.

It still works.

JavaScript creates the variable named apples and stores the value 8 in it despite no previous variable declaration and without the var keyword.

Avoid this practice since it can lead to confusion later in larger scripts. Use the var keyword:

var apples = 8;

Even though the script works without var, using the var keyword is good practice.

Variable Naming Rules

We cannot name a variable anything we want. There are rules to follow that prevent syntax errors and ambiguities.

Identifier Rules:

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

4. Keywords and any other reserved words are not allowed. For example, you cannot name a variable var since var is a keyword reserved by the JavaScript language itself.

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.

Assignment Operator

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.

The assignment operator used in variable assignment is right-associative, meaning the flow is from right to left.

JavaScript Data Types

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

JavaScript supports data types too. Three of the most common are numeric, string, and Boolean.

  • 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

JavaScript is a loosely typed language.

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.

With JavaScript, the situation is different. We do not declare data types for variables, and we can store any data type in any variable. If a variable begins as one that stores an integer, we can later assign a floating-point value to it.

var number = 100;
number = 200;
number = 300.34567;

In fact, we can even assign a string to the number variable.

number = "Hello, World!";

This is valid JavaScript because JavaScript is a loosely typed language. Variables are not tied to a specific data type in JavaScript like they are with Java.

Valid JavaScript. A variable is not constricted to a specific data type.

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.

This happens frequently. It might seem insignificant in the beginning, but a “one or the other” state occurs so often, that JavaScript has a data type devoted to it.

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.

A light switch with two states, On or Off, is an example of a Boolean data type.

true and false are case-sensitive with lowercase true and lowercase false. Do not use True or False since these will return errors.

true and false are case-sensitive in JavaScript.

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

Here is an example involving a Boolean variable. We can display a modal dialog using the confirm() method. The full declaration is window.confirm(), but JavaScript assumes that window is the default object if no object is specified.

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.

Confirm dialog in Vivaldi.

  • OK = true
  • Cancel = false

The return value is stored in the variable choice, which is displayed in the console.

OK button clicked.

 

Cancel button clicked.

Conclusion

JavaScript, as well as most programming languages, depends upon variables for operation. It is almost impossible to write any useful program of length without them. For something so important, the information presented here is all we really need in order to use them. Yes, variables are that easy to use in JavaScript.

For now, experiment using your own JavaScript variables, and have fun!

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: