Intro to Web Programming - Javascript Pt. 2

So you’ve got some interesting data you want to work with. You’ve figured out your favorite way to store it using Javascript. What kind of things can you do with it? Well that’s up to your imagination, but let’s start with the tools!

First let’s fire up an environment where we can play around with Javascript. As in part 1, I’ll recommend using JS Bin with only the Javascript and Console panes active.

Playing with Variables

Javascript is a pretty flexible language, and one of the interesting things you can do with it is play around with your variables after running your code.


In the Javascript pane, type this:

1
var favoriteNumber = 5;

This will store the number 5 into the variable favoriteNumber as you’d expect. Press the Run button in the Console pane.

…Nothing happened, right?

Wrong. What just happened was you stored a number into the variable, but didn’t do anything else with it that would produce a message or any visual output. It actually did what you asked.

How can you tell? Easy, through the magic of the Javascript console:

Looking at Variables

You should notice that at the bottom of the Console pane that there is a > marker. This is a prompt where you can type in commands directly to the Javascript interpreter.

Go ahead and click near that marker and type in favoriteNumber - Don’t worry about typing console.log or anything else, just put in the name of the variable you used in your code. Press enter.

The number 5 should show up on its own line and you’ll be brought back to your > prompt.

This is how you inspect the state of your variables. If you tried to do it before running your code it would say undefined because it doesn’t know anything about your program.

This works with objects, arrays, and pretty much everything else (assuming it’s simple enough to be represented in the console).

Try it out with an object:

1
2
3
4
var person = {
name: 'Brent',
status: 'Blogging'
};

Type that (or copy/paste it) into the Javascript pane on the left (either on a line after or completely replacing the favoriteNumber code). Press run.

Now click back on the Console pane by the > marker and type person and press enter.

You should see something like this:

1
2
3
4
[object Object] {
name: "Brent",
status: "Blogging"
}

You can see that it has automatically identified what we put in the person variable as being an Object, perfect!

Digging a little bit further

So we have an object, a fairly simple one at that. But what if we don’t want to look at the whole thing, what if we just want to get a little piece of information from inside of it?

Introducing Dot Notation!

Go to the Console pane if you’re not still there.

Type person.name and press enter.

You should see just the name showed up! This is how you access things inside of objects.

Tip: These named attributes of an object are called ‘properties’ or ‘keys’. Whenever you hear someone say “Key-Value Pair” you can think of how you accessed the value “Brent” from the key “name”.

This works for deeply nested things too, if our object looks like this:

1
2
3
4
5
6
7
8
var person = {
name: "Brent",
location: {
city: "Kelowna",
province: "British Columbia",
country: "Canada"
}
};

You could find out the country I live in by typing the following into the console:

person.location.country and then press enter.

“Canada” would be returned in this case.

What about arrays/lists?

Dot notation is wonderful, but it only works for values of Objects. If you have a list of things, say:

1
2
3
4
5
var favoriteThings = [
'computers',
'crafting',
'movies'
];

And you want to grab just one thing from the list, you can ask for the values by index.

An index is a numerical value that represents which ‘slot’ of the list a value sits in. These indexes start at 0, and go up from there (the last one ends up being the number of things in the array minus 1, since it all starts at 0)

To get the first item from the array, type this (in your Console pane after running the code above) and press enter:

1
favoriteThings[0];

It should spit out “Computers” in your console.

Hint: You can actually use the square bracket format for Objects too, it looks like this: person["name"]; Just don’t forget the quotation marks!

Changing variables after they’ve been set

They’re called variables for a reason, because they can vary/change whenever you need them to.

Let’s go back to a simpler example, erase everything in your Javascript pane and put the following in:

1
var favoriteNumber = 5;

Hit the run button, and click over to the Console pane and type favoriteNumber and press enter. It should show 5 as you’d expect.

What if 5 isn’t our favorite number anymore? In the Console type in this:

1
favoriteNumber = 8;

You’ll see that it spits out the number 8 right afterwards, this means it has changed the value for you!

Note: You don’t need to put var in front in this case, because favoriteNumber already exists and you’re just changing it.

Being a wordsmith

Numbers are one thing, but words are another! It’s really simple to build sentences and modify text.

Let’s say you have:

1
var name = "Tom";

What if we wanted to build a simple greeting for Tom? You can add words, much like you can add numbers:

1
2
var name = "Tom";
var greeting = "Hello " + name + ", welcome to my website!";

If you were to run that and type greeting into the Console pane, you would get:

Hello Tom, welcome to my website!

as output. Now things are getting a tiny bit more exciting!

Performing math on variables

Let’s say you wanted to increase your favoriteNumber by one, you can do that by typing in the following:

1
favoriteNumber = favoriteNumber + 1;

Woah, wait a sec! If you look at that, you’ll see that you’re setting the variable to itself plus 1. This is completely okay, and in fact you could set it to the value of some other variable if you wanted. In this case we just chose to use its existing value (of 8).

If you want a shorter version of this, it looks a little something like this:

1
favoriteNumber++;

If you type that in, you may notice the number being spit out in the console is always 1 behind — that’s because it’s outputting it before it makes the change. You can make it increase before it outputs the value by using this code instead:

1
++favoriteNumber;

It’s a subtle difference, but it’ll matter later on.

There are a bunch of other math operations you can do such as:

Subtract 1:

1
favoriteNumber = favoriteNumber - 1;

Multiply by 2:

1
favoriteNumber = favoriteNumber * 2;

Divide by 2:

1
favoriteNumber = favoriteNumber / 2;

These are some of the basics and you can use values other than 1 and 2 if you like!

Changing contents of lists and objects

Just like simple variables, you can change the values inside objects and lists.

If you have an object like this:

1
2
3
4
var person = {
name: "Brent",
status: "Blogging"
};

You could change the status by doing this:

1
person.status = "Sleepy";

With objects you can actually add new keys/properties to it as well!

1
person.nickname = "Seratonik";

If you have a list like this:

1
var niceColors = [ "Red", "Blue", "Taupe" ];

And you wanted to change Taupe to something better you could do this:

1
niceColors[2] = "Green";

Remember: We use the index of 2, because the list starts at 0.

But I’m just doing this in the Console?

The console is a sandbox where you can play to your hearts content with your program’s values, it won’t save anything. But every single command you type in is completely valid Javascript. You can take any of the things you’ve typed in the console and put them in your Javascript pane underneath the code that’s there to have it saved as a permanent part of your program.

Mixing and Matching Variables

It’s pretty boring just adding, subtracting and doing other basic math on variables. It is however very common. But let’s get to some more interesting things.

Variables that are based on other variables

Let’s say you want to calculate how many seconds are in a year. You could break it down like this:

1
2
3
4
var secondsPerMinute = 60;
var minutesPerHour = 60;
var hoursPerDay = 24;
var daysPerYear = 365;

Now we have all of our components of time broken out into neat names (this is a sort of self-documenting form of code because it’s readable and has a clear intent)

If you put that in your Javascript pane, and click Run in your Console then you can start typing things like this into the console:

1
secondsPerMinute;

You’ll see it spit out 60. Okay, simple enough. What if we want the number of seconds in an hour?

1
secondsPerMinute * minutesPerHour;

This will print out 3600! We just multiplied the two variables and the result got put in the console. We can keep extending this now to give us the seconds in a year:

1
secondsPerMinute * minutesPerHour * hoursPerDay * daysPerYear;

A whopping 31536000 seconds!

Well there’s no reason to only do this in the Console pane. Let’s save that result to a new variable in our code. Click on over to the Javascript pane and add the following to a new line at the bottom of the code we already have:

1
var secondsPerYear = secondsPerMinute * minutesPerHour * hoursPerDay * daysPerYear;

Now if you press run in the Console pane, and then type secondsPerYear in the console, you’ll get the same result we got when calculating it before.

Thoughts: These values won’t change on planet Earth and might seem silly to store in variables, but if you wanted to calculate how many seconds were in a year on Mars, you could change each of the variables involved in the calculation separately and re-run to get your newly calculated value!

Combining Things for Mind-bending Fun

Okay.. so one of the most interesting things about programming is the fact that everything basically just takes input and produces output (that then can be input for other things). It’s so simple that we often overlook the power of it.

Let’s set up a seemingly complex example, erase everything and put this in your Javascript pane instead:

1
2
3
4
5
var person = {
name: "Brent",
favoriteThings: [ "computers", "games", "movies", "crafting" ],
favoriteNumber: 1167
};

We discussed in this article the idea that we can ask for values using keys/properties of an object via dot notation (Ex. person.name to get the name in this case). We also learned that we can use square brackets to ask for a specific item from a list, and we can mash variables together to make more complex things.

If I wanted to make a sentence, perhaps saying what I most enjoy, I can combine all these theories together like so:

1
var sentence = person.name + " enjoys " + person.favoriteThings[0] + " and " + person.favoriteNumber + " is their favorite number.";

Take a good long moment and look at the different components of that:

1) First we start with person.name, Javascript figures out the value for us - it outputs “Brent”
2) Then we add another piece of text to it: “ enjoys “ - The language no longer sees person.name, it basically sees it as the result instead, which is “Brent”. Resulting in “Brent enjoys “ at this point.
3) Then we add person.favoriteThings[0] - This is new, we’re kind of asking for two things here, first we ask it to find person.favoriteThings which is a list of things. So it’ll start by grabbing that list, and then after it has the list it sees the [0] afterwards, meaning we want the first thing from the list. In this case it’s “computers”, now the list no longer matters, it’s found what it needed and so the result is added together with the rest to make “Brent enjoys computers”
4) The text “ and “ gets added to our string now, so we have “Brent enjoys computers and “
5) person.favoriteNumber is simple dot notation, but this time it’s not text we’re adding, it’s a number! What happens when you add a number to text instead of adding it to another number? In Javascript it treats it like it were text. So now the string reads: “Brent enjoys computers and 1167”
6) Now we just finish off the sentence with another string. The final result is:

Brent enjoys computers and 1167 is their favorite number.

In this case we stored that in a variable called sentence. Since the value is calculated at the time you make the variable sentence won’t magically change if you change any of the values that made it up afterwards (unless you also remake the sentence variable after doing so)

Summary: Basically you should never be afraid to play with concepts, they’re all inter-changable. You could in theory do something like this (even though you’d probably want something more manageable):

people["Brent"].friendsList[0].hobbies[3]

“Grab the 4th hobby of the first friend in Brent’s friend list” (assuming all that data was pre-filled out in the correct structure)

Review

Now you know how to create variables, peek at their values, make changes to them and combine them. Slowly but surely your arsenal of tools is increasing. Pretty soon we can start building some real world applications!

Stay tuned for more parts to this intro to Javascript!