Javascript 101: Working with Variables

Welcome back for another session of Javascript 101. After having looked at all the different data types in Javascript previously, this post will introduce you to the concept of working with variables in your code. You've most likely already encountered the variable x in several math classes during your time in school. At that time we were looking at simple mathematical equations such as

5 + x = 10  

In this case, x would be substituting any value that could make the equation true, for example 5. In Javascript, we can assign a value to a variable name by using the keyword var

var myVariable = 5  

This would initiate a variable called myVariable with the value 5. I could now continue in my program and write

console.log(5 + myVariable)  

console.log() is a useful function that enables us to log data to our console. If you are following along on repl.it, this should output 10 on your console to the right. Now instead of myVariable we could use all kinds of names.

var x = 4;  
var iceCream = 10;  
var blueshoes = 2;  
var y = 12;  
var myVar = 22;  
console.log(x + iceCream + blueshoes + y + myVar)  

Now, if you didn't make any errors in your spelling, your console.log() should show the result of our calculation - 50. Note that you cannot use hyphenation in variable names. Words like my-super-long-variable would throw out an error in your code. To still be able to use longer variable names, the general consent is the so-called camelCase style. This means you capitalize the first letter of every word but the first. For example: mySuperLongVariable or iceCreamBox, doTheseThings, myVar, getMeFood. You get the idea.

In Javascript we can have a lot more fun with variables than just using them for numbers and calculations.

var age = 20;  
console.log("I am " + age + " years old"); // "I am 20 years old"

var name = "Tobi";  
console.log("My name is " + name); // "My name is Tobi"

var firstName = "Peter";  
var lastName = "Parker";  
console.log(firstName + " " + LastName); // "Peter Parker"

var x = 5;  
var y = 10;  
console.log(x * y); // 50  
console.log(x + x + x) // 15  
console.log(y > 8) // true  

We only need our special var keyword when we first initialize our variable. Initializing means that we are creating a new space in the memory of our computer for that variable. After that first creation of the variable, we can assign or change value without using var.

var myVar = 5;  
console.log(myVar); // myVar is 5  
myVar = 6;  
myVar = "text";  
console.log(myVar); // myVar is "text"  
myVar = 33-5;  

All code in Javascript is flowing from the top to the bottom. We are logging our variable myVar to the console at several times during this process of changing it in our program. Our logs are showing the value of myVar at the moment it was logged, not the value it had at the end of the program. Unlike in languages such as C, we can change the data type of a variable without any issues from a string to an integer and back again. Instead of assigning new values to your variable, you can also increment, decrement and modify it.

var myVar = 10;  
myVar = myVar + 15;  
console.log(myVar); // myVar is 25  
myVar += 10; // a shorter way to write 'myVar = myVar + 10'  
console.log(myVar); // myVar is 35

myVar = myVar - 5;  
console.log(myvar); // myVar is 30  
myVar -= 10; // again, shorter way to write 'myVar = myVar -10'  
console.log(myVar); // myVar is 20  

If we try to use our variable before it has been declared, we will get an error in our console. We always need to define variables before we work with them.

console.log(myVar); // causes an error  
myVar = 5;  

I hope you haven't forgotten about arrays and objects yet. Both of these data types can be assigned to variables as well.

var myArr = ["red","blue","green","pink"];  
console.log(myArr[2]); // logs "green"

myArr[0] = "fish"; // assigning different a value to the first index in the array;  
console.log(myArr); // logs ["fish","blue","green","pink"]

myArr[5] = "carrot"; // adds a new value to the array;  
console.log(myArr); // logs ["fish","blue","green","pink","carrot"]

myArr[20] = "dog"; // element will be inserted at the next available position  
console.log(myArr); // logs ["fish","blue","green","pink","carrot","dog"]  

So far so good. Before wrapping this up, let's take a final look at objects.

var myMusic = {  
    artists: ["Incubus","Metronomy","The Decemberists"],
    favoriteArtist: "Muse"
};
console.log(myMusic.artists); // logs ["Incubus","Metronomy","The Decemberists"]  
console.log(myMusic.favoriteArtist); // logs "Muse"  

The dot notation of objects has a major downfall. I can get into trouble if I want to access my object properties with variable names. Imagine you have just asked your user to tell you if he wants to filter for his favorite artist or all artists...

var myMusic = {  
    artists: ["Incubus","Metronomy","The Decemberists"],
    favoriteArtist: "Muse"
};
var selectedFilter = "favoriteArtist"

console.log(myMusic.selectedFilter)  

Now, we might think that we want to pass this string "favoriteArtist", which we've received from our user to our myMusic object. However, all we get is an "undefined". This is due to the fact that the dot notation doesn't care for your variables. It will take your variable name (selectedFilter) and look if there are any properties with that name in myMusic (there are none). So, how do we fix this? By using the bracket notation.

var myMusic = {  
    artists: ["Incubus","Metronomy","The Decemberists"],
    favoriteArtist: "Muse"
};
var selectedFilter = "favoriteArtist"  
console.log(myMusic["artists"]);  
console.log(myMusic[selectedFilter]);  

The bracket notation allows us to enter variables instead of a string. Perfect for cases in which we want to use dynamic values to look up properties of objects.

This ends today's Javascript 101. Now that we've learned to work comfortably with several types of data and variables in our code, we will move on to even more exciting topics such as functions and methods in the next lessons. You might ask yourself right now, how all this will finally contribute to building interactive websites. Fair question - we will get there soon. For now, rest assured that building a strong foundational knowledge of the language will later help you to be creative and bring your ideas to life when we start working on our first website.

Until then, leave your thoughts in the comments. Feedback, suggestions, and ideas are much appreciated.

Further down the rabbit hole