Declaring a variable – an alias name for a memory location - AT THE GATES OF ENLIGHTENMENT - JavaScript in Plain Language (2015)

JavaScript in Plain Language (2015)


1.3 Declaring a variable – an alias name for a memory location

Preliminary information:

Browsers use computer memory. The more memory a computer has, the faster the browser works. Since working memory is limited, programs need to constantly rearrange data in memory by deleting what expires and repositioning what is still in use.

When we program in JavaScript we store data in memory. This data is short lived since once we close the browser or end the program, the data is wiped out.

To temporarily store data in memory we need to label the memory address location with a word that makes sense to humans, so that we can program or manipulate that data. We can’t just tell the browser to store the string of characters “hello world!” in memory by giving it the address of0x7fffffff. Those days are long gone as it would be too complex and unpractical as well as ever changing since data is shifted around from location to location due to automatic memory rearrangements. So to address this problem, we use names as alias for assigned locations and allow the computer to manage the real physical address of the data as it sees fit.

Those memory location aliases are called variables. The reason they are called variables is twofold: the address of the data can be changed without notice, and the data contained in each variable can also be changed at any time. What remains constant is the variable name, which is the only link humans have to this piece of memory real estate.

As for the change of a value in a variable, that may be either done manually by the programmer further down the script instructions, or automatically by JavaScript itself in a dynamic reassignment of values.

· Know this: To create a memory variable we have to declare it (declaring a variable is like introducing the variable to JavaScript). Example:

var phoneBill;

(Just read along. You will have a chance to try it yourself when we get to the Lab Work section at the end of the chapter. All chapters are purposely short. This is the time to read and understand conceptually. Then you will test yourself during lab. All lab exercises are followed by the correct answers so that you can double check your work).

About var

Think of var as the command used to create a variable (this helps you remember to use var when you introduce a variable.

Another thing that var does is to ground the variable to the location where it is being introduced, sort of like making it a local variable (more about that later).

About the variable name

After writing var we provide the variable name which in our case is phoneBill. The name does not matter, it could have been called x since JavaScript does not care about the ‘human meaning’ we choose to give it.

However, JavaScript cares about the choice of characters we use. Make sure the first character is a lowercase letter of the alphabet (the lowercase is not mandatory, just good practice as you will see later). The variable cannot start with a number or a symbol. Subsequent letters can be numbers, but symbols are not allowed, ever, except for the underscore _.

· In summary: always start your variable names with a lower case letter. Forget about the underscore as the first character because it is usually used in very special situations and therefore should not be considered for normal usage.

My own variable phoneBill has a capital B in the middle. This is a common style of writing variable names. JavaScript doesn’t care about styles, but it does make it easier for the human eye when it comes to inspect the script.

Another popular way of writing names is with an underscore separating the ‘human meaning’ of each word in the variable name. The reason for the underscore is because spaces or dashes are not permitted in variable names: phone_bill

· Remember this: The ‘meaning of a word’ is only for human consumption. If instead of introducing phoneBill we introduced just x, JavaScript would have accepted it without complaining. When we program, we do it both for the computer to understand and also for a human to understand so that he/she can troubleshoot or update the program later. Choose your own style of writing variables and stick to it. Consistency is important. However, become familiar with all common styles because when you work in a team you need to adjust to an agreed common style for the whole team. Practice flexibility.

About the semicolon ;

The semicolon at the end of the statement tells JavaScript that you are done declaring the variable:

var phoneBill;

The semicolon acts as a command terminator, or a separator between two different and independent commands. In other words, we are instructing JavaScript to stop and save that command or expression as an independent instruction from the next upcoming instruction.

Going back to the variable name,

· Keep this in mind: JavaScript is case sensitive. A and a have independent meanings in JavaScript. phoneBill and phonebill are not the same word. At this moment phoneBill is an existing declared variable, and phonebill is nothing, JavaScript will throw an error if you write phonebill by mistake instead of phoneBill since you have declared phoneBill as the variable, and not phonebill.

Of course we could also have two independent variables, one named phoneBill and another named phonebill and that is the point, for JavaScript they are two different words.

Adding data to variables

Once a variable is declared, a memory location is reserved for that variable and then we can assign the variable to some data.

Isn’t it easier to just remember phoneBill rather than making a written map of reserved memory locations?

To assign data into a variable we use the = operator:

phoneBill = 200;

Do not use $ before 200. That would trigger an error. You may use $ later when you output the data if you so wish, but not when you enter your data into the computer memory. All JavaScript wants is the number 200 in its pure form.

I have just saved the number 200 in a memory location listed as phoneBill. Notice the semicolon at the end. It terminates my statement.

We could have declared and also included the data in just one-step:

var utilitiesBill = 400;

Sometimes we just want to tell JavaScript to reserve a location under a certain name. Other times we reserve the location and fill it with data all at once. Don’t worry about the size of memory needed. Contrary to other languages, JavaScript is dynamic: it adjusts the memory automatically.

Changing the value in the variable

What if we want to change the value of our phoneBill from 200 to 150?

To change the value of a variable all we have to do is to reassign it (no declaration needed):

phoneBill = 150;

The 200 gets deleted and the computer memory at location phoneBill now holds the value of 150.

· Remember this: Never use var twice on the same variable name. If you use var as a prefix when you rewrite an existing variable, you wipe out the old variable since you have just re-declared the variable again. This may be something you want to do on purpose, but for the most part, this is not a common practice. I have seen this done many times as a mistake by new programmers.

Adding words to a variable instead of numbers

So far we have been assigning data of type number to our variables. We can actually assign anything to a variable.

Since a variable is just a memory location, we can assign it a string of characters also known as a value of type string, or even other types of data such as arrays, functions, objects... more about those later.

Let’s talk about strings

A string of characters can be assigned to a variable but we need to let JavaScript know it is a string. The way we let it know, is by wrapping our string of characters in quotes:

var myName = "Tony";

Any word not wrapped in quotes is considered to be a reserved term stored in the JavaScript library.

· If I just write var myName = Tony; (with no quotes for the string ‘Tony’), JavaScript will check its library in the computer’s memory looking for a command or a variable named Tony. Since Tony does not exist as a reserved term, JavaScript will throw an error on the screen. Any word data needs to be wrapped in quotes.

After we declare the variable myName, the word myName then becomes a reserved term until it gets wiped out from memory or until the program is over. No quotes for variable names.

· Remember this: Data of type string needs to be wrapped in quotes as opposed to declared variables names which are never written in quotes.

When I say “remember this” it doesn’t mean to memorize it. It only means to focus a few seconds of extra attention to the statement that is about to follow.

Which quotes to use: single or double?

In JavaScript, a pair of single or double quotes work the same way. Just make sure the closing quote matches the style of the opening quote. Some other languages act differently in single or double quotes; not JavaScript.

Below you will find another variable declaration and value assignment all at once. You will see how combining quotes can be useful. I start with a single quote, followed by a double quote. However JavaScript ignores the double quote because it knows the closing quote must by single in order to match the opening quote:

var quoteOfTheDay = '"living is not essential; creating is essential" - Fernando Pessoa';

· Remember this: Never wrap a variable name in quotes. If you do that, you convert the name into a string. I mean, quoteOfTheDay and "quoteOfTheDay" don’t have the same meaning for JavaScript. The first one is a declared variable stored in the JavaScript temporary library. The second one is just a plain string of characters. JavaScript will not map it to the memory location assigned to quoteOfTheDay.

Assigning variables to other variables

We have seen already how to reassign a variable to a new value:

phoneBill = 600;

Now, phoneBill is no longer 150. It holds the value of 600.

What about assigning a variable to another variable?

It works the same way as assigning a regular value:

phoneBill = quoteOfTheDay;

Note: No quotes are being used because both words are previously declared variables. The real value, which is a string value, is being passed inside of the variable quoteOdTheDay.

· Remember this rule:
Assignments work from right to left. What is on the right gets assigned to the left operand.

The value of phoneBill has now been changed from the numeric 600 to the string "living is not essential; creating is essential" - Fernando Pessoa.

Basically, JavaScript copied the string value from quoteOfTheDay to phoneBill. We now have two strings of the same value in two different memory locations. This copying is not always true as we will see later. Copying only happens with primitive data types, such as numbers and strings. When we reassign complex data such as arrays and functions, also known as reference types, we do not duplicate the data; we just point those two variables to the same data. But this is an advanced concept. For now, just think of duplicating variable values when we reassign a variable containing simple data to another variable.

We will see more about primitive and reference types later in the book. Sometimes I throw in terms without an explanation. The idea is to get you used to the term as common language when you read along and without memorizing it. A former introduction will happen at the appropriate time. Occasionally you will see a link to sources such as Wikipedia. The link is there in case you want to explore the topic further, but no external link it essential in order to understand the material we are covering. Wikipedia is my favorite source of general information for two reasons: It gets updated quickly and it does not have annoying popup commercial messages.