Just the weekly tutorials.

JavaScript Variables

Learning isn?t always about explaining new complex subjects. Sometimes it?s about bringing to your attention the deeper details of the already known. In-depth understanding makes programming more interesting. It?s easy to think that you know everything about variables. But there are many details that often slip from the viewfinder of an untrained eye.

While working on Revision Two of my new jQuery book, I have added more chapters to the JavaScript Bootcamp section where I talk about the basics of JavaScript programming.

One of the subjects deals with JavaScript variables. To learn more about JavaScript I?d like to invite you to download my PDF book which breaks complex subjects down into smaller, easy to understand parts. This newsletter is an excerpt directly from the 2nd revision of my book and today I?d like to give you a glimpse into some of my current work.

One of the goals with my writing is to give a deeper insight into simple concepts. I believe that by reaching down to the very reason for why something works a certain way the reader is given an opportunity to become a better JavaScript programmer.

When teaching a computer language such as JavaScript, numerous tutorials talk about using variables in terms of showing how they work. But little is said about what they are. We are often told that we can define variables using the var keyword. But understanding what they are and where they come from gives us a deeper insight into JavaScript programming. In fact, many JavaScript concepts, such as objects, are much easier to understand if we can compare them with variables.

Are They Variables or Objects?

Because everything in JavaScript is an object this sometimes creates confusion among the beginners who are seeking to understand JavaScript data types. If everything is an object, then what is a variable? And if a variable is indeed an object, then why are we using the keyword named var to define it? Wouldn?t something like obj be more appropriate?

The answers to such questions are often determined by creators of the language specification itself. The fact that someone decided to create a specification does not guarante that this specification will be ideal. Regardless, when it comes to any data in any language, it is always tied to the same concept: all data is stored in computer memory on the microprocessor.

Keep in mind that all variables are physically stored in computer memory at random addresses. When we access a variable, we access the part of computer memory it is stored in. A variable is stored at a unique and random memory address chosen by the operating system.

We?ll get to how variables are physically stored in computer memory in just a moment.

Even though it is possible to omit the var keyword from a variable definition, I recommend to always define your variable with the var keyword:

var apples = 1;

Let?s take a look at some of the basic principles behind variable definitions:

Variables are not unique to JavaScript. In other languages variables are created using all kinds of keywords. In PHP a variable name is prepended a dollar sign as in $apple. In C++, each different type of a variable has its own keyword. For example int for an integer type, char for a text character or short for ?half? a variable which is 2 bytes in length. 4 bytes would be a full 32 bit set. On a 64-bit computer processor, an integer is 64-bit long.

In JavaScript we use the var keyword to define a variable of any type. How does JavaScript determine the type of a variable being created? The type is defined by the assigned value. If we say that apples = 1, JavaScript automatically creates a variable of type integer.

Determining Variable Type

JavaScript variable definitions are typeless. This means that we can create any type of a variable and during the program lifecycle we can overwrite it by assigning a new value to it. This new value doesn?t have to be of the same type as the original. In comparison, this wouldn?t be true in languages like C++, where a variable of type integer can only be assigned an integer value.

Typeless variables such as ones used by JavaScript can be reassigned, or turned into a different type using the equal sign. In C++ this process is known as type casting and requires manual action. But this is completely legal in JavaScript and happens automatically. To check the type of a variable at any point of its existence, we can use the typeof function:

typeof number, string, boolean, object, null, etc. diagram

A variable allocates enough data storage in memory to store its value:

javascript variable apple / ram

The actual data is stored as 0s and 1s on the microchip. Even though in the example above the variable named apple equals 1, on a 32-bit processor a set of 32 0s is created. We?ll get to binary logic in a bit. For now just think of variables as values stored at a unique memory address.

The truth is that even variables defined with the var keyword are objects. But because it is possible to start using variables to manipulate data by learning their simple syntax, many people never bother studying them with a greater degree of depth.

I have discussed objects in a pervious newsletter. However, this newsletter is a full chapter exerpt from my book. Many other tutorials, including understanding objects are explained in even greater detail in my jQuery tutorial book (in PDF format) that you can order from my website. This book is frequently updated with new content and all updates are free after you order your copy. The price of the book is increased with each update. However, there is a current promotion that will help you get it for only $25 and qualify you to receive all subsequent updates for free.

Variable Data Storage, Memory and Operators

You are probably already familiar with JavaScript operators like the plus, minus and multiplication signs. They allow us to do common logical operations on integers and even strings. But as we just discussed above, the nature of a variable is in its physical representation in memory.

In memory, a variable is not stored as a name as seen in a JavaScript program. The name apple exists only as an alias to the physical location in memory on the microchip. This value is represented as a long string of 0s and 1s on the microchip at a unuque memory address. Knowing this becomes incredibly important if we are to understand how bitwise operators work.

We?ll get to the bitwise operators in a following editions of my newsletter that you should receive in about 2 days from now. Sit tight :-)

The actual value of a variable exists at a unique address in memory. The name apple is an alias to that address. For us humans it is easier to communicate in words and phrases than in numbers, like computers do. The name apple is a reference to a unique address that could look something like 0xFA074315 in hexadecimal (base 16) number system.

In other words, var apple = 1, is the same thing as 0xFA074315 = 1. This hexadecimal address is chosen by the operating system at random, as our program executes. It is the RAM address. This makes sense now why this memory is called RAM, or Random Access Memory. It?s because variables and other computer program data is stored at a temporary random address.

Let?s do a simple review to show how this relates to JavaScript code. Let?s assume that we have a variable var apple = 1. Let?s compare it to actual representation in computer memory:

binary vs decimal simple example

Even though the stored value is 1, all those other zeros are still part of the same integer called apple. They are just not being used. This is because the minimum size of an integer on a 32-bit computer is 32 bits long. This is just how data is stored in computer memory. The 0s and 1s are actual physical switches on the microprocessor. Of course if you are on a computer with a 64-bit processor, the integer would consist of 64 bits or 8 bytes. This gives us more processing power but that?s beyond the subject of this book.

That?s a lot of 0s. To access or manipulate them, we can use the bitwise operators. But before we get to bitwise operators its essential to understand how binary numbers work.

In order to understand binary numbers it?s a good idea to start with an example that explains what happens when we increment a value of a binary number by one unit. There is a certain pattern that forms. I broke down the proecss of incrementing a binary number into steps.

Shortly, we will take a look at these steps in detail. However, before looking at these diagrams you should understand a few important things.

Let?s increment the binary value 00000001 (which is 1 in decimal) by one unit.

binary increment diagram

Do you want to really understand programming? Or just write a few scripts and forget it? Binary logic is an incredibly important concept. It may seem complicated at first, but I assure you that by taking just 10 minutes to look at how binary logic works, a whole new world of possibilities will open up and you might start seeing things in a slightly different way.

You and I have been using the decimal counting system from our birth. Decimal means base 10. Perhaps counting up to 10 and starting over as in 11, 12, 13, 14, 15 and so forth came from the fact that human beings have 10 fingers. Whether that?s true or not, I don?t know. But if we look at it that way, then a computer processor only has 1 finger. And it can either raise it like a flag by showing that a bit is set to 1 or hide it by showing us nothing, or 0.

How would you count if you only had one finger? That seems to be like the only way. But computers have memory that has enough space to store many values. So using this finger ballet the computer operates on large data sets even though it only has one finger to do it with. How does it then store values in memory? By using one finger to flip some values on and others off, across the entire memory board.

Since we know that in a binary number a value can be only 0 or 1, then changing that value is always a toggle. If a value is 0, it can only be changed to 1. If a value is 1, it can only be changed to 0. We flip bits like they are lightbulb switches.

The computer can flip any bit of information at any time if you instruct it to do so. Which bits will you want to flip on or off? That?s entirely up to you. But when it comes to incrementing a binary number by one unit, there is a certain pattern that forms. Knowing this pattern will probably not make you a better JavaScript programmer. But it might give you a deeper insight into how computer work.

* * * * *

Human beings become fascinated about control. When I was 12 years old, my uncle showed me how to draw a line on a computer using the BASIC language. I can tell you that this event alone fascinated me so much (I could now draw lines on the screen of a computer!) that I saw myself making video games. It motivated me to continue exploring the world of computer programming. It let me know that I could control the screen by issuing commands. It was fun.

The knowledge of binary numbers may not be necessary for most tasks associated with web development but knowing that this kind of thing goes on inside a computer can awaken the inspiration in someone. I hope, in the same way that my uncle awakened it in me.

We have already discussed that to increment a binary number by one unit we shift 1 to its left, opening up more room for zeros to its right. But we have only discussed this process in the context of going from 1 to 2. How do we go from 2 to 3 in binary logic? Let?s take a look, because we don?t just keep shifting the leading 1 to the left in this case. Something else happens.

Incrementing a Binary Number

Here is a diagram that explains how to increment a binary number one bit at a time.

How to increment a binary number

Just the weekly tutorials.