This is the third part of my Learn to Code series. The previous part is here: Chapter 1 – Meet Bob.

## See Bob. See Bob Run. Run Bob, Run!

We last spoke about making Bob run 5 miles. We were going to do that by performing an action – a “function” in programmer parlance – called “run”, and give the number 5 (meaning the miles he is to run) to the function. We do that like this:

bob.run(5);

The problem is, we haven’t said what “run” actually means or does. Later we’ll use code that already exists but this time it’s all up to us. We’re going to have to write this “run” function ourselves. Again, this is a very easy thing to do once you understand the pattern you use.

function (miles) {
}

Here we say we want to create a “function” and that the function will take some information in brackets that we can refer to by the name “miles”. You see, when information (such as the number 5) is “passed” into the function, it is important that we can get to it because we can use it to change how the function operates. You can write a function once, but pass different things to it each time and it will behave differently every time. That is the real beauty of programming.

You will notice there aren’t any semi-colons in the bit of code above, this is because we are using a pattern that the computer will understand – those curly brackets (called “braces”) tell the computer when you’re starting and stopping to describe your function. However, when we write code inside those braces, we still must use semi-colons to differentiate one .

The devil is very much in the details when programming. Different programming languages have different requirements for WHERE those curly braces go. Sometimes they should be on the same line as the start of your function, and sometimes they go on the next line down. Like this:

function (miles)
{
}

But the language we are learning needs them to be on the same line as the word “function”.

Here’s an example of combining curly braces and semi-colons. Gosh it’s getting complicated… but stick with it, this is as complex as it gets. let’s write some code inside the function that uses that number 5 that was passed in, which we can refer to as “miles”:

function (miles) {
return miles + miles;
}

This is now a fully-functioning function. If you’ll pardon the pun. Although… not a particularly useful one. Yet.

We have written a function that takes some information that we refer to as “miles”, and then the function performs some calculation on that information (doubling it) and then “returns” it to whomever ran the function in the first place.

Note that if you pass the number 5 into this function, you get 10 returned. But if you passed something else, like 50, you’d get 100 returned back to you.

## Members Only

In programming, the annoying thing is that you hardly ever get anything for free. You have to tell the computer EVERYTHING. It really is true what they say – computers don’t make mistakes, humans do!

Right now we have written a function, but it’s an orphan, floating through space without a name (remember, we want it to be called “run”) or an owner. We now need to give  “Bob” this function, and finally christen it as the “run” function. This is very, very easy to do and builds upon the previous stuff you’ve learned.

You shouldn’t be too surprised to see that the way we do this is with an equals sign (which we’ve used before to “set” information):

bob.run = function (miles) {
return miles + miles;
}

We’re saying that bob has something called “run” and we “set” (or “assign”, if you want to use the proper programmer jargon) a function to that name. Equals is very important. You use it to populate a set of properties on your “objects”. You can assign words, numbers, functions or other objects using the equals sign. There’s no difference between setting a property and assigning a function:

bob.age = 30;
bob.run = function (miles) {
return miles + miles;
}
bob.spouse = betty;

We call these properties “members” because they belong to Bob.

## Nesting Functions

You also can put functions inside of the brackets of a function.

Let that sink in.

This means that you can create a function that performs a calculation which returns its result directly into another function’s brackets. It is easier to show you what I mean than explain (as I said, almost everything in programming is easier than it sounds).

bob.run( bob.run(10) );

Here we are simply using the same function twice. Functions are run from the innermost to the outermost. This makes sense if you think about it, because you need to get the inner function to return its value before that result can be passed into the outer function!

Before I explain the above line of code, try and work out what the value you will end up with.

[pause tape]

OK, we can run through it, step by step.

The innermost function is given the number 10. Then it doubles it. To 20. (Duh).

THEN! Then that result (20) is passed into the “run” function again, so it gets doubled once more to 40.

Easy peasy.

## “Global” Functions

Sometimes it makes sense to write a function that you don’t want to assign to an object such as “bob”, and instead you’d like it to be available everywhere in your code. One example of this is the function that you use to make a message alert appear on the screen:

We are calling the “alert” function, without having to use an “accessor”, and we give the function a bunch of words to show on the alert that pops up. Click here to see it in action!

The quotations tell the computer when you are starting and stopping your text. They have a very similar job to semi colons and curly braces. If we wanted the alert to say “You have just run the alert function!”, then without the quotes, when the computer gets to the last word in that sentence, “function”, it wouldn’t know if you wanted to say the word function in the alert message or if you were actually writing a new function! Yes, computers are dumb.

Some words have a special meaning such as “function”, we call them “keywords” or sometimes “reserved” words. Basically, you can’t add a function to Bob called “function” because that would cause all sorts of problems when the computer was trying to figure out what you meant!!

The take-away from this section of the lesson is: if you want to pass words into functions, put quotation marks around the words!

What if you want to show a quotation mark in your alert? Like this? Easy. You simply have to let the computer know that you aren’t actually using the quotation mark to end your text. You need to override the quotation mark’s special meaning by “escaping” it. (Let me show you instead of struggling like a mad teapot to try and explain it):

Before you write any quotes that you want to pass to a function, and don’t want the computer to think means the end of your text, you simply put a back-slash. Easy peasy. Lemon squeezy.

And what is I want to write a backslash in my alert message? Won’t the computer just think I’m “escaping” something?

Easy, you escape the backslash with (wait for it) a backslash! So you put two backslashes in order to get one out:

alert("This sentence has \\ a backslash in it!");

## OH MY GOD SHUT UP AND LET ME WRITE SOME CODE

OK! OK! Keep your pants on. Two final things.

One, remember how I said you get nothing for free? Well, we never actually told the computer that Bob was something. We never assigned “bob” to mean anything. We have to tell the computer that he is an “object”, and objects are the things that you can put properties and functions on. Telling the computer that “bob” is an object is as simple as assigning an open-curly-bracket and a closed-curly-bracket to the word bob:

bob = {};

This “initialises” (creates) bob as an empty object. And finally, let’s change our “run” function to be something more appropriate:

function (miles) {
alert("Bob has just run " + miles + " miles.");
}

Briefly, because I know you’re dying to write some code properly today, this introduces a few new concepts that you need to know:

• Functions don’t always need to “return” something. This new “run” function doesn’t return a thing, it simply shows an alert message!
• In order to mix expressions (such as words and our “miles” number) you use the plus sign. Plus means “add” but it also means “concatenate”, which is unnecessarily-complex-programmer-speak for “join together”.
• Be careful when displaying some text that mixes expressions and words – one of the most common mistakes is forgetting to put a space before and after an expression. For example, you want to make sure your message says:”Bob has just run 5 miles.”and not…”Bob has just run5miles.”

You may think that’s a stupid mistake to make, but when deadlines loom and you’re making coffee every thirtieth keystroke, it can be a very common problem.

Actually, that’s another thing, if you’re not addicted to coffee, give up now. We will not accept you into our Programmer Collective. You have been warned! 🙂

OK, it’s time to open up Notepad, or your favourite text editor (NOT Microsoft Word! Something simple. Wordpad, Write, emacs, Notepad++, something like that will be fine).

Write the following, which is the culmination of all our work so far:

bob = {};
bob.age = 30;
bob.run = function (miles) {
alert("Bob has run " + miles + " miles.");
} ;

bob.run(5);

Not a lot to show for three lessons work, but you’ve come a very long way already. You can dissect the lines above and explain why they are the way they are.

The question now is how do we run this code?

Well, the programming language we’ve been writing in is JavaScript, a very common way of making website dynamic (Facebook, Twitter, etc. all use JavaScript to make themselves much more interactive and include live-updating).

So we need to save this text file as a web page. But as web pages can not only contain JavaScript, but also many other things too (videos, pictures, walls, porn, etc.), you need to “wrap” the JavaScript code in something that tells your web browser (Internet Explorer, Google Chrome, Mozilla Firefox, Apple Safari, etc.) where the code starts and stops (like semi-colons, curly braces and quotation marks – can you see there are patterns emerging here?). You don’t need to understand it fully yet, but just for now, add the following text at the top of your text:

<script type="text/javascript">

and this at the bottom:

</script>

To do this, save it as “UTF-8” and with a “.html” file extension (the bit on the end of the file name). So it’s easy to find again I’d recommend you save it to your desktop for now.

## Learn to Code: Our first program in its entirety

So your file should look like this:

<script type="text/javascript">
bob = {};
bob.age = 30;
bob.run = function (miles) {
alert("Bob has run " + miles + " miles.");
} ;

bob.run(5);
</script>

Save the file, and then double-click on the file wherever you saved it (the desktop?).

You should see a browser window pop up and then an alert box will appear:

Our work here is done. You’ve written your first program!

But I don’t think this is the last we’ve seen of “bob”…