JavaScript Variables
“JavaScript variables are containers for storing data values. Variables are named containers that you can place data in and then refer to the data by naming the container.”
“The variable statement declares a variable, optionally initializing it to a value." - MDN
Let’s look at some code to see how to declare a variable, initialize a variable along with naming best practices and more! At the end of this article I will share how to can practice this in the Google Chrome Console.
var animal;
animal = "horse";
Declaring a Variable
Let’s look at declaring a variable in JavaScript by breaking down this first line of JavaScript:
var animal;
First, we have the keyword var
. In JavaScript there are keywords that are reserved words letting the JavaScript interpreter know what you want to do. Here, the keyword var
let’s the JavaScript interpreter know that you are declaring a variable.
Next, we have the variable name animal
. This is sometimes called the identifier or target.
Finally, we have a ;
. In JavaScript the semicolon allows the developer to signify the end of a statement.
// var -> keyword
// animal -> name, target, identifier
// ; -> signifies the end of a statementvar animal;
Initializing a Variable
Now, let’s look at initializing a variable. Following our variable name we have the assignment operator =
to assign a value to our variable.
Pause, what is an assignment operator?
Assignment operators (JavaScript) An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=).
In the following example we are assigning the variable animal
the value a string, a JavaScript data type, "horse”
.
animal = "horse";
Once we have declared a variable we can continue to change its values.
animal = "cow"; // value of animal set to the string "cow"
animal = false; // animal set to the boolean false
Declare and Initialize at Once
Previously we declared a variable and then after we declared it we initialized it with a value. However, we can do both of these at once.
var transportation = "car";
Declare and Initialize Multiple Variables at Once
We can declared and initialize multiple variables at once. We need only to use the var
keyword once then separate our variables with a ,
.
var animal, vegetable, fastFood; // Orvar animal = "cow", vegetable = "carrot", fastFood = "hamburger";
In one line we can use the var
keyword to declare our variables of animal
, vegetable
and fastFood
and initialize their value to the string "cow"
for animal
, "carrow"
for vegetable
and "hamburger
for fastFood
.
Variable Names are Case Sensitive
var animalcookies
is not the same as var animalCookies
. Feel free to try the following in a text editor prove to yourself that JavaScript variables are case sensitive :)
// declare and initialize variable animalcookies to the number 10
var animalcookies = 10;// declare and initialize variable animalCookies with a capital "C" // to the number 15
var animalCookies = 15;animalcookies; // 10
animalCookies; // 15// use conditional statement to ask if these two values are the same.if (animalcookies === animalCookies) {
return true;
} else {
return false;
}
Variable Naming Rules and Best Practice
Variable names can contain letters, digits, underscores, and dollar signs such as in the examples below.
var rougeOne; // contains letter(s)
var rouge1; // contains number(s)
var _rouge1; // contains underscore(s)
var $_rouge1; // contains dollar sign(s)
Illegal variable naming
Names cannot begin with a number, have a space between words, contain special characters or use JavaScript reserved keywords.
While numbers can be contained within a variable name eg rouge1
they are not an acceptable way to begin a variable name. Words must not have spaces and will most commonly be brought together with camel case as we will discuss in variable naming best practices soon. var
is a JavaScript reserved keyword along with class
, do
, else
, function
for example.
var 1rouge; // begins with a number
var rouge one; // has a space between words
var rouge*one; // contains special characters
var var; // JavaScript reserved keyword
Best Practice — Camel Case and Human Readable
As we have seen previously variable names can begin with $, _ and letters. The letters can be upper or lower case. However, best practice, and you will find exceptions to this in the future is that your variables generally should be named camel case style. Camel case style has you capitalizing the first letter of each word in a multi-word variable name starting with the second word.
var costPerTransaction; // Camel Case
In this case we skip capitalizing the “c” in “cost” but we do capitalize the “P” in “Per” and “T” in “Transaction”.
var costpertransaction; // acceptable - bad practice
In the example above all three ways were acceptable means for naming a variable. However, using camel case for the last object where you capitalize the first letter of each multi-word variable starting with the second word makes for the most readable name.
Below, are several more examples of different ways to naming multi-word variables. Kebab case, like meat and vegetables on a stick has your words separated with a hyphen, giving the impression that their is a stick running through them. Pascal case is when you intentionally capitalize the first word instead of starting it lowercase. Snake case is when you separate words with an underscore.
If you are just getting started with JavaScript begin with consistently naming your variables with camel case style as a best practice.
var firstName; // camel case - Best Practice for Beginners
var first-name; // kebab case
var FirstName; // pascal case
var first_name; // snake case
Human Readable
When you are writing JavaScript you must write in a way that the JavaScript interpreter can understand. Your computer will be very picky and seemingly has no ability to read your mind and what you are attempting to do. Your computer is pretty dumb in that way.
We just spent some time talking about how you need to specifically name your variables and things to avoid so that your computer can understand what you are doing.
However, aside from writing for the computer you are also writing code for yourself and those coming after you. It will be a common occurrence that someone looks at your code to fix bugs or make improvements and you are writing for them. Also, you will find yourself going back to your own code looking to fix bugs and make improvements.
Keep this in mind when you name your variables. When possible your variable name should communicate the data that it contains.
Your computer understands the following very well x = 25;
and you may as well as you are writing this code. However, if you came back to look at your code in a couple weeks or months you may see that x = 25;
and not be exactly what x
refers to.
To make this more human readable you might name this numberOfApples = 25;
. You have stuck to the syntax rules that the JavaScript interpreter can understand but you have also given your variable a name that a human interpreter can understand.
As you grow in your use of JavaScript in the future you might find yourself running a minnifier in which a program will reduce all of your variable names when you code is sent to production. The minifier may very well in the end change a variable name like numberOfApples
to x
but you can let a minimizing program do that when the time is right. You should leave yourself guessing what a variable represents.
Dynamically Typed Language
This means that you don’t have to define what the variable data type is.
var transportation = ‘car’; var passLieDetector = false; var groceryBill = 74;
You don’t have to tell variable transportation that car is a string. It knows it. You don’t have to tell var passLieDetector that false is a boolean, it knows it. And you don’t have to tell var groceryBill is a number. The JavaScript interpreter will know what to do with the value that you pass to is.
This is called Dynamic Typing.
If we do a typeof on all our variables JavaScript can tell us.
typeof transportation = ‘car’; // "string"typeof passLieDetector = false; // "boolean" typeof groceryBill = 74; // "number"
There you have it, thanks for looking at variables with me and if you want to practice, take a look at the next video!
If you enjoyed this article you will love my courses! Check them out here.