With variables, you can start to unleash the full potential of JavaScript. In fact, they are the main item that allows your code to work dynamically. With them, your code can do different things in different circumstances. In other words, you absolutely need variables. In this Javascript tutorial, we will see what are variables, and how to use them.
If you are new to Javascript, this tutorial is for you! However, if you have no clue on how to create a Javascript file or how to run it, you should read our Getting Started with JS tutorial first.
Introducing Variables
Variables are not something unique to Javascript. Indeed, pretty much every programming language has the concept of variable. That’s simply because they allow you to process and store data very simply. But what is a variable exactly?
To answer this question, we can start with a use case. In coding, like in math, you process data and obtain some results. In both cases, the processing is deterministic, so the same initial values will always result in the same results. Take the following example.
2 * 5 + 1
This operation always equals 11
, no matter what. So why should we execute this calculation every time? We could just write the result, and save some time. However, take a look at the following tweak:
2 * x + 1
Now, we have no predefined results for this calculation. In fact, the final result will vary depending on the actual value of x
. If x
is equal to 5
, then we will result in 11
, just like before. However, if x
is equal to, say, 3
, we will result in 7
. In this example, x
is a variable.
Variables are placeholders. You can picture them as boxes that contain a value. You can then reference to placeholder – the box – in any part of the code. In this way, you will tell Javascript “open the box and use whatever value you find in it at this specific point in time”. Yes, because the content of the box (the value of the variable) can change over time.
Reading & Writing Variables
You can do just two things with a variable: reading it or writing it. These operations are pretty simple.
Reading a variable simply means getting its value. Getting what’s inside the box, and using it for our calculation. Whenever you write your variable in a formula, Javascript will basically read it on-the-fly when calculating the formula.
Writing, as you can imagine, is the opposite. With this operation, you actually specify the value to put inside the box, overriding the existing one. In general, this is done by having your variable at the left side of an equal sign (=
), but more on this later. Writing to a variable is also known as assign a value.
In addition to those operations, there is one special type of write. In fact, the first thing you want to do with a variable is to inform Javascript that that variable exists. That’s because, as we will see, you can pick any name you want for a variable. When you first create the variable, you are declaring it. And, during this operation, you can also specify an initial value. In fact, a declaration is just a special type of assignment.
Variables in JavaScript
It is time to dive into writing some code! The following sections will show how to create and use variables in JavaScript.
Declaring Variables
As we know, the first thing we want to do is declaring the variable. With this operation, we inform Javascript about the existence of the variable. Each variable, each box, has a name, and that name is a word. Declaring the variable informs the JS engine that, every time it encounters that particular word, it should open the variable and look for its value.
To declare a variable, you use the var
construct.
var myVariable = 1;
With this statement, we defined e variable with the name of myVariable
, and gave an initial value of 1
. After this line, we can start to use it in our code. Below, an example.
alert(myVariable * 2);
You don’t have to define an initial value necessarily. You could also just declare the variable with no value, and assign it later. In that case, simply write the name of the variable with the var
keyword, as follow.
var myVariable;
You cannot declare the same variables twice! In othe words, the name of a variable must be unique. If two boxes have the same name, in fact, how is JavaScript supposed to know which of the two to open?
Naming Variables in JavaScript
You can use pretty much any name you want for a variable. However, there are some basic (and common-sense) rules that you must follow. To start, you can only use letters, numbers, and underscores. Obviously you cannot use spaces, quotes, hyphens, or any other type of special characters.
In addition to that, the very first character of a variable should not be a number. However, any other character can. Take a look at the following examples of good names vs bade names.
These names are valid.
myVariable
my1stVariable
_1
_variable
VARIABLE
Variable123
Variable_Variable
variable_1_Var
Instead, those other names are invalid.
1stVariable
My Variable
My-Variable
MyVariable*
Var?
Another thing you want to consider is casing, which is how to combine lowercase and uppercase letters. This is crucial when your variable name contains multiple words (for example myVariable
is My
and Variable
).
- With camel case, you write everything in lowercase but the first letter of each word, except the first one (e.g.
thisIsACamelCasedVariable
). You should use this casing in JavaScript! - Pascal case is similar to camel case, but you uppercase also the very first letter (e.g.
ThisIsAPascalCasedVariable
). - Snake case uses underscores to separate words, and it is all lowercase (e.g.
this_is_a_snake_cased_variable
). - Kebab case, instead, uses hyphens to separate words (e.g.
this-is-a-kebab-cased-variable
). However, as hyphens are not valid as part of variable names in JavaScript, this is not available to use.
The best practice tell us to use camel case. Even more important than that, you should be consistent. Always use the same style through all your files in your project, so that the code remains clear.
Assigning Values to Variables
Now that we have declared our variable, we want to assign them a value. That’s extremely simple to do. We simply use the =
sign, where on the left we find the variable that will receive the value, and on the right the value we want to assign. For example:
myVariable = 5;
Once we execute this code, the value inside myVariable
will be 5
. We can see it changing if we use alert()
.
var myVariable = 1;
alert(myVariable); // 1 will appear
myVariable = 5;
alert(myVariable); // 5 will appear
You can take this assignment to the next level, by assigning the value of a variable to another variable. In this way, you Javascript will open the source variable, read its value, and copy it into the destination variable as well. To do that, simply use another variable on the right of the =
sign.
var source = 5;
var destination;
destination = source;
alert(destination); // 5 will appear
source = 10;
alert(source); // 10 will appear
alert(destination); // 5 will appear, as we re-assigned only source
Working with Value Types
In our previous javascript tutorial, we saw there are several value types for a variable. We can quickly summarize and expand on it. In fact, a variable can be of a simple or complex type. The simple types are the following.
- String represents a piece of text, you should wrap the value between quotes (e.g.
"my value here"
). - Number represents a numeric value, on which you can do mathematical operations. Simply write the number, and to separate decimal positions (if any), use a dot (e.g.
1
or23.044
). - A boolean represents a flag, a status that can be either true or not. You can, in fact, use only two values:
true
, andfalse
. null
is a special type that indicates the absence of value.undefined
is a special type that indicates the variable does not exist.NaN (Not a Number)
a special type to indicate when an operation fails because a number was expected, but a different type was found.
In addition to the simple types, we have complex types. Those are a composition of multiple simple types together, but we will see them later in our Full Stack Development course. They are beyond this Javascript variables tutorial for now.
Javascript does not have strong types. It means that a variable containing a string can later contain a number, and so on. So, in the declaration, you are not forcing a variable to contain only values of a specific type. Furthermore, you should consider the following operations.
var a;
a = 1 + 4; // 5
a = "string1" + "string2"; // "string1string2"
a = "a" + 4; // a4
a = "1" + 4; // 14, "1" is a string so we cannot perform math on it
a = 4 * 4; // 16
a = "a" * 4; // NaN
a = "4" * 4; // 16, automatically converts the first string
Reading and Debugging Variables
As we know, whenever we use the name of a variable in a formula, we are reading from it. So, take a look at the following example.
var b = a + 1;
In this example, we are reading the value of a
, while assigning a new value to b
. As you can see, in a single line you can do one assignment and one reading (and potentially more than one reading).
However, what if we want to actually see the content of a variable? That is useful when we are trying to understand if our code is working properly or not. We know that with alert()
we can generate an annoying popup, but that’s not the best option in most cases.
Instead, we can use console.log()
. This will basically generate a log in the console, a particular part of the Developers Tools on your browser.
var variable = "This is a message";
console.log(variable);
To open the console on your browser, right-click on any part of the web page and select Inspect Element (if you are on Firefox), or Inspect (if you are on Chrome). Alternatively, in any browser, you can press F12 on your keyboard. Look for the Console tab, and you will see the log as follow.
Variables Like a Pro in JS
Variable Scope
For now, the Javascript file looks just like that: a file. A file where you can throw all your code together. In reality, to create complex behaviors, things are a little bit more complex than that.
Different pieces of code can have a different hierarchy, and variables can live and thrive in that hierarchy. Specifically, the more you go down into the hierarchy, the more you are specific.
If you define a variable with the var
keyword, it will be available at all levels of the hierarchy, no matter where you define it. However, you can use the let
keyword alternatively. With that, the variable is available only at the current level and at the more specific levels. In other words, it has a narrower scope.
An example will make things clearer. Just know that a code block is a piece of code between curly brackets, and that the if
construct allows you to check a condition and execute the code inside its code block only if the condition true.
var largeScope = "I am available for everyone";
var a = 1;
let b = "Works";
if (a == 1) {
largeScope = "I am available even at a more specific level";
var smallScopeGlobal = "I am still accessible from the outside";
let smallScopeOnly = "Sorry!";
}
console.log(largeScope);
console.log(smallScopeGlobal);
console.log(b);
// This will give error (because it was defined with let)
console.log(smallScopeOnly);
Additionally, you have another keyword you can use to define variables: const
. This means constant, and you cannot reassign a value to variables of this type. They are constant indeed. You can use them as a reference (e.g. const pi = 3.14
), but you generally use those with complex objects. In fact, you cannot reassign these variables, but the object they contain may mutate. That’s something you simply cannot do with simple types.
More on Variables’ Naming
We know that we should follow the camel casing. However, just picking the right case is not enough to create variables in the proper way. You should follow some rules to make your code clearer:
- Self-explanatory names – the name of the variable must tell what it contains (bad name:
a
, good name:username
). - Broader Scope? Larger name – if you use a variable only inside a code block, and you can see all the places where you use it with one glance, then it’s fine going with a short name. However, if your variable appears all over the place, be generous with its name. Do not sacrifice words (bad name:
cnt
, good name:wishlistProductCount
). Instead, for smaller scopes, a short name is more than welcomed (in that case,cnt
would be preferred). - Prefer
let
tovar
– this is pretty much self-explanatory. You want to do this so that variables are local to where you need them, and they are not available all over the place. - Use verbs when needed – mostly in variables representing a status (e.g.
isActive
,isLoggedIn
,hasAuthorization
).
Remember, computers will just process the code. Humans will read it (yourself included). You should write code for humans to understand, not for computers. And even if you think nobody will ever touch it again, you will – and you will forget for sure. And even if you think you won’t, eventually you will. So do yourself a favor, and write good and clean code by following those rules.
JavaScript Variables for Full Stack Developers
As you know by now, we are running a Full Stack Development Course. This JavaScript tutorial is part of it, and we like to test our knowledge by putting things into practice. We can do this as well, by working on our pretend bakery website.
However, for now, we don’t have much to put in action, as variables alone cannot do much magic. Still, we are going to try by creating a message that should appear in the console. This message should be stored in a variable, named according to all best practices we saw in this tutorial. So, you should not print directly the string, you should use a variable first. Checking the logs in the console, we should see something like this:
Implementing this behavior should be pretty straightforward. Nonetheless, if you need help you can find the solution below. Be aware, because in the very next paragraph you are going to see the solution, and you should try this on your own first.
Okay, so here’s the solution in just a two-lines code snippet. You need to have this in your script.js
file.
var logMessage = "I am a log message for Full Stack Developers!";
console.log(logMessage);
You can check all the code from our pretend bakery website on GitHub.com at alessandromaggio/full-stack-course. Furthermore, you can see the changes we did specifically for this javascript tutorial in this commit.
In Conclusion
Variables are a crucial pillar of Javascript and of any programming language. With this tutorial, you know what they are and how to use them effectively. You have now everything you need to start tackling dynamic behaviors in Javascript and customize what happens on your pages.