Hi, I'm Nicholas Johnson!

software engineer / trainer / AI enthusiast

Learn to Code with JavaScript

A Sensible Introduction to Coding with JavaScript

By Nicholas Johnson

Document Version: 2.0.2

Last Updated: 23th September 2023

Workbook Cover Image

Hello There & Welcome to JavaScript!

Hello there new programmer! If you’ve never programmed before, you’re in for a treat because this is the book for you! In this book, we’re going to be covering the very basics of JavaScript from the ground up. These are the fundamentals that you will need to know to do the fancy stuff that you’re probably quite keen to get started on shortly.

So allow me to say:

Welcome new programmer, to a whole world of wonder!

Coding is like Hobbits. You can learn all that there is to know about its ways in a month and yet, after a hundred years, it can still surprise you.

This book will teach you the ways of code. The fundamental pieces that we all use. It won’t teach you how to make a Twitter clone in thirty minutes, instead it will teach you about variables, loops, functions and arrays, the foundational building blocks that everything we do is built upon.

Computer languages are all pretty similar. Learn one and you’re well on the way to learning more than one. What differs is the syntax and the culture. Luckily JavaScript has lovely syntax, and an awsome culture full of brilliant folks who will go out of their way to welcome you into the fold.

We were all new coders once. With time and patience you will become the master, and then it will be down to you to welcome new coders, just as I was welcomed, and now I welcome you.

JavaScript is everywhere

JavaScript is the most widely deployed language in the world by an order of magnitude.

You will find it:

  • In your web browser (in pretty much every laptop, desktop and smartphone in the world, probably more than once)
  • In a mobile webview powering the apps on your smartphone - many mobile apps are built using JavaScript, including Facebook, Slack, Discord and many others.
  • On your server - NodeJS provides a complete and powerful web server used by some of the biggest companies in the world, companies like Microsoft.
  • In your front end development environment - JavaScript powers Webpack, Rollup, Yeoman, Bower, SASS and many other tools front end developers rely on.
  • In desktop apps - like VSCode, Slack, and many others.

You can use JavaScript to build pretty much anything you like.

JavaScript is rather good (which is lucky really)

Bjarne Sandstrup once said, “There are only two kinds of languages: the ones people complain about and the ones nobody uses.”

JavaScript is often misunderstood. It is different to most other languages out there. This is because JavaScript comes from a different evolutionary branch than most other languages.

Most modern languages descend from C. JavaScript is actually a dialect of LISP with C syntax layered over it. It is a rare and beautiful fusion, but because it is different, some people misunderstand it, and this misunderstanding sometimes leads to hatred. This is a mistake because JavaScript is wonderful.

Its heart is rooted in a love of freedom. Many other languages will try to lock you into a paradigm. They will say to you, “This is how you should code. Do it this way and you will be safe.” JavaScript does no such thing, it happily supports any programming paradigm you want to throw at it. More on this later.

Are you a maths person who likes functions and mathematical purity? Maybe you like to think in terms of physical objects? Maybe you like to think in terms of events taking place over time? Do you just want to hack together a script to automate something? JavaScript lets you choose your poison, or mix and match. This is a blessing and a curse, because with freedome comes the potential to make mistakes. You will need to learn different styles of coding to navigate this language.

Don’t worry if this makes no sense to you yet, in time it will.

Exercise: Saying Hello to JavaScript

This is the first exercise. Exercises are scattered throughout this book, you’ll recognise them because they come in a little box. In this exercise, we’ll be saying hello to JavaScript. Of course, the JavaScript won’t actually hear us saying hello, unless we shout really loud…

You should do these exercises. Coding is like playing an instrument. Reading about it doesn’t really help much, you have to actually do the work with your hands.

Create some HTML

The easiest way to run JavaScript is in a web browser. You just create a web page, then open it in a web browser. The JavaScript will run automatically.

First of all we’ll need to make a web page for our script to live in. Open your favourite code editor (VSCode is never a bad choice). Create the following ultra simple html document and save it in a folder. Call it hello.html. Now double click it to open it in a web browser like Chrome or Firefox.

<!DOCTYPE html>
<html>
  <head>
    <title>Hello JavaScript</title>
  </head>
  <body></body>
</html>

Write some Script

Next, create a document to contain your JavaScript. Save it in the same folder as your html and call it hello.js.

alert("Hello JavaScript, your new best friend!");

Hook them up

Now, we need to link the two together. In the head of your HTML document add a script tag like so:

<script src="hello.js"></script>

(Note that the script tag cannot be self closing. You have to explicitly close it with an </script> tag or it will fail.)

What do you get?

Now, referesh the page in your browser. You should see a handy little box pop up welcoming you to JavaScript!.

Exercise - more alerts

Extend the code so it pops up two alerts.

So what did we do here?

  1. We created an HTML and a JavaScript file, and linked them together.
  2. We used the built in alert function to pop up little box containing the text “Hello JavaScript, your new best friend!“.

Well done! You just created your first JavaScript program!

Don’t string me along…

The next thing we should know about is strings. A piece of text in JavaScript is called a string. It’s a string of letters all attached together. We can tell it’s a string because it sits between quotation marks like this:

"I am a String";

Everything between the quotes is part of the string and will be treated by JavaScript as a piece of text, and not part of your program.

We can also use single quotes too, like so:

'I am a String';

We can add strings together to make longer strings using the plus character:

"Hi there " + "hello";

Alerting

If we need to know what’s inside a string we can find out using an alert box like so:

alert("Hi there " + "hello");

Add this to your script and press refresh. Nice!

One of the ways we can use strings is to help our program talk to our user. We saw this in the first example in the last section. We used an alert box to display the string “Hello JavaScript, your new best friend!“. Strings have a whole host of uses that we’ll come too soon.

console.log

We can also get data out using the console object. We write:

console.log('Hi from the console');

The console is a developer tool. On Windows you can open it by pressing F12. If you’re on Chrome you can right click, select inspect, then choose the console tab. You’ll be able to see all kinds of information about your program here and you’ll be using this a lot going forward.

Exercise - Let’s alert some strings

Nice and simple this one. We’re just going to create some strings and pop them up in little boxes.

  1. Put the phrase “Hello there JavaScript” in an alert box.
  2. Put the phrase “Hello there Java” + “Script” in an alert box.

Strings are objects

Objects are little balls of related data and functionality. We can access information stored in an object using a dot (.).

Let’s get the length of the string. We can do it like this:

"Allo allo allo".length;

We might even alert this:

alert("Allo allo allo".length);

Exercise - Monkey with Strings

  • Write a program that tells me the the number of characters in your name.
  • Tell me what 123+456 is. Now tell me what “123” + “456” is. Weird?

Numbers and strings are different from each other. 123 + 456 adds the numbers together/ ‘123’ + ‘456’ glues the strings one after the other. Strings are sequences of letters.

Variables - buckets of fun

Imagine for a moment your program is a bit like a kid on a beach making a sandcastle. The kid is going to need lots of raw materials to make that castle, sand, little shiny rocks, pebbles, flags, water from the sea. This kid isn’t like the other children see? This kid is ambitious.

The kid is going to need somewhere to keep all of those raw materials. He’s going to need some buckets. Probably a whole bunch of buckets.

Variables are like JavaScript buckets. We can store things in them until we need them later, and we can use the bucket in place of the thing that’s inside. We can create them very easily and have as many as we like.

We can tell JavaScript to make a variable just by putting something in one, like this:

let greeting = "Hi there!";
alert(greeting);

We have put the string “Hi there!” inside a variable (bucket) called greeting. Then we have alerted greeting. What does this do?

Changing the value of a variable

We can change the value of a variable any time, just by assigning a new value to it, so we could write:

let name;
name = "Dave";
alert(name);

name = "Susan";
alert(name);

The variable called name contains first the string “Dave”, and then the string “Susan”. Dave is now renamed Susan. Hopefully he is OK with this.

Variables are containers

Imagine I have a basket full of kittens, now when I hand you that basket, I’m actually handing you a bunch of kittens. This is probably a pleasant experience for you.

We can codify this snuggly basket like so:

let basket = "kittens";

Now the basket can stand in wherever we previously needed kittens. For example, I could write:

alert("kittens");

or I could write

alert(basket);

Either way I would alert some kittens.

Variables are pointers

We can also think of variables as pointers (actually this is more accurate). If I stand pointing at a basket of awsome kittens all happy and soft, and say look at this, you’re probably going to look at the kittens rather than my finger. The variable stands in for the data.

The data exists in a physical location on the memory chips inside your computer. The variable points at that location, and the computer is clever enough to ge fetch the information and substitute it for the variable.

Variables are a bit like maths, but also not

In maths, if I say x = 12, I’m stating something that is true, immutable and forever. When I write x, I actually mean 12. x + x is the same as 12 + 12 which is 24.

Variables in code are a bit different, we can change their value, because they are just pointers to some data, and in code we can change our data any time.

I can say:

let x = 12;

then later I can say:

x = 13;

This is totally fine, we’re yous storing some different data in the variable.

I can say:

x = x + 1;

Now x = 14. None of this is allowed in maths, but in code it’s no problem. The values of variables are just numbers in a big memory chip full of numbers. We can change them to anything we like and no one will stop us.

Variable names

Variables can be called almost anything you like. Hamster, pie or cheeseOnToast are all perfectly sound variable names. The one restriction is that you can’t have any spaces or maths characters in them. You can’t have a variable called cheese on toast for instance, or a variable called five+five. This would confuse JavaScript and give it a headache.

Don’t worry about giving your variables long and descriptive names. This is encouraged as it makes your code easy to read. Too long though and you’ll spend a lot of time typing. It’s a balancing act.

Although we can call our variables anything we like, it makes our lives easier if we give them sensible English names or common abbreviations.

The Let Keyword

Please note that when we first create a variable we must always remember to use the let keyword. If we forget it, bad things will happen. More on this when we get to Scope. For now, just remember to put them in.

## Exercise: Thanks for all the fish

Variables are like little buckets in which we can store any information we like. Let’s pop a string in one, and then pop it out in an alert box.

  1. Create an HTML document and linked JavaScript file.
  2. In your JavaScript file, create a variable called farewell and give it a value of “Thanks for all the fish”
  3. Pop your farewell variable up in an alert box.

Answers

To answer this question, first we create a variable, lets call it greeting, and assign a value of “Thanks for all the fish” to it. The variable greeting is a bucket that contains the string. We can now use it in place of the string, and alert it.

let greeting = "Thanks for all the fish";
alert(greeting);

Exercise: What’s for dinner…

  1. Create a variable called question. Give it a value of “What’s for dinner?”
  2. Create a variable called answer. Give it a value of “Fish”
  3. Add the two variables together and put the result in an alert box.

Answers

Variables are buckets. We can use variables in place of the things they represent, so:

let question = "What's for dinner?";
let answer = "Fish";
alert(question + answer);

If we’d like to improve the output slightly we can separate the two with a space:

alert(question + " " + answer);

Maths Operators - Doing Sums

JavaScript is great for maths. Lets say we need to know what 3 times 5 is. We can just ask JavaScript:

alert(3 * 5);

So handy! You’ll never need a desk calculator again. We can also combine maths with our new found knowledge of variables like so:

let slices = 12;
let slicesNeededForASandwich = 2;
let numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);

Note the that a forward slash (/) means division.

Maths characters

The following special characters are used when doing maths in Javascript.

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Test for greater than: >
  • Test for less than: <
  • Test for equal to: ===
  • Brackets can be used as in maths to separate a part of the equation. ( )

There are a few more that you might need later, but these will do for now. These characters are the same in almost every programming language you will come across.

Exercise: Doing Sums

  1. Create an HTML file and linked Javascript file.
  2. Output 5 - 2 using an alert box
  3. Output 6 * 9
  4. Output 6 * 9 + 4
  5. Output 6 * (9 + 4)
  6. Output (1 + 1) * (1 + 1)

Answers

  1. alert( 5 - 2 );
  2. alert( 6 \* 9 );
  3. alert( 6 \* 9 + 4 );
  4. alert( 6 \* (9 + 4) );
  5. alert( (1 + 1) \* (1 + 1) );

Exercise - equality

  1. Try this now, alert 1 + 1 === 2, what do you get?
  2. Now alert 5 + 5 === 10 What do you get?
  3. What if I were to do this instead: 5 + (5 === 2). Whoah, that’s weird. Why did you get this result?
  4. Now try 5 + (5 === 5). Also weird. Why did you get this result? You’ll find out more when we get to Booleans.

Answers

  • The braces force the right part of the expression to be evaluated first. Unlike maths, === is just an operator, the same as + or -. 5 === 2 is false.
  • 5 + (5 === 2) is the same as 5 + false. JavaScript doesn’t know how to do this, so it converts the false into zero and gives you 5 + 0 which is 5
  • 5 + (5 === 5) is the same as 5 + true. JavaScript doesn’t know how to do this either, so it converts the true into 1 for “historical reasons” and gives you 5 + 1 which is 6.

Exercise: Sandwich Calculator

  1. Create an HTML file and linked JavaScript file.
  2. Enter the following code:
let slices = 12;
let slicesNeededForASandwich = 2;
let numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);
  1. Find out how many sandwiches you can make?
  2. You have taken a large job lot of bread, 800 slices in total, and it’s starting to go stale. Quickly adjust the code to find out how many sandwiches you can make with all that bread.
  3. You decide to make Club sandwiches for a swanky dinner, and you need 3 slices for each. Adjust the code to find out how many sandwiches you can make with those 800 slices?
  4. There’s a problem with the delivery and some of the bread comes damaged! You estimate 10% it is no good! How many slices do you have now? How many sandwices can you make?

Answers

If you have 800 slices, you need to change the value of the slices variable like so:

let slices = 800;
let slicesNeededForASandwich = 2;
let numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);

To find out how many club sandwiches we need, all we need to do is change the value of slicesNeededForASandwich from 2 to 3. We will now get the correct answer.

let slices = 800;
let slicesNeededForASandwich = 3;
let numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);

To estimage the 10% damage, you can just multiply slices by 0.9 to get the usable slices that remain.

let slices = 800 * 0.9;
let slicesNeededForASandwich = 3;
let numberOfSandwiches = slices / slicesNeededForASandwich;
alert(numberOfSandwiches);

You did it! Horray for maths and Horray for you!

We need to do this sort of thing all the time in JavaScript, whether we’re working out the size of a page element, writing a handy little VAT calculator for our online shopping cart, or deciding to increase our spend on Google AdWords.

Now on to functions…

Functions - doing things more than once

Mrs. Potts is the school dinner lady. Today is the school trip, and it’s her job to make sandwiches for all the children. She has to make a lot of sandwiches, and each one takes some work. The bus will be arriving soon and Mrs. Potts is worried she might not finish. Some of the children might not have enough food to eat. Hurry Mrs. Potts!

To make a sandwich Mrs. Potts has to:

  1. Get some bread
  2. Spread the butter
  3. Spread the jam
  4. Cut off the crusts
  5. Put it in a little bag

We could write a program to help her to this, it might look something like this:

console.log("Get bread");
console.log("Spread butter");
console.log("Spread jam");
console.log("Cut off crusts");
console.log("Put in a little bag");

Exercise - Poor Mrs Potts

  1. Create an HTML file and linked JavaScript file.
  2. Enter the above program and run it.

Help Mrs. Potts. The bus will be here soon. Time is running out!

Who will help Mrs Potts?

This is all very well, but Mrs. Potts has to make 40 sandwiches and we’ve only made one. To make 40 could take a lot of typing. What if there was a way to help her by wrapping up all the actions needed to make one sandwich into a single reusable function, something we could use over and over 40 times, 100 times even. Well…

Wrapping it all up in a function

Lets make a few changes to our program above.

let makeSandwich = function () {
  alert("Get bread");
  alert("Spread the butter");
  alert("Spread the jam");
  alert("Cut off the crusts");
  alert("Put in a little bag");
};

makeSandwich();

What have we done here? Well, you may have noticed that we’ve created a new variable called makeSandwich.

The variables we have created so far have contained strings or numbers, see the section on variables if you need a refresher, but variables are buckets remember and they can hold any type of thing. In this case we have said that the makeSandwich variable should be a new type of thing called a function.

A function is a little ball of code, all wrapped up neatly so that we can use it again and again. After creating our function and assigning it to the makeSandwich variable, we can call it by writing:

makeSandwich();

The parenthesis (brackets) mean that we want to treat the variable as a function. We can run the function as many times as we like. Just call makeSandwich() again and again, as many times as we need it.

Exercise - Making five sandwiches

  1. Create an HTML file and linked JavaScript file.
  2. Enter the code above carefully and run it.
  3. Add the line makeSandwich() again five times to help Mrs. Potts make five sandwiches. We’re still a little way off…

Answers

let makeSandwich = function () {
  alert("Get bread");
  alert("Spread the butter");
  alert("Spread the jam");
  alert("Cut off the crusts");
  alert("Put in a little bag");
};
makeSandwich();
makeSandwich();
makeSandwich();
makeSandwich();
makeSandwich();

Marmite sandwiches - Passing Parameters

This is all excellent, but oh dear, Mrs. Potts has just remembered that some of the children have asked for Marmite sandwiches because they are allergic to jam. Our function can only make jam. What will we do? Will the children still go hungry?

What if there was a way to tell our function what filling we want? Thankfully there is. We are going to use Function Parameters. Let’s change our program like so:

let makeSandwich = function (filling) {
  alert("Get bread");
  alert("Spread the butter");
  alert("Spread the " + filling);
  alert("Cut off the crusts");
  alert("Put in a little bag");
};

makeSandwich("marmite");
makeSandwich("jam");
makeSandwich("squeezy cheez");

See, we have changed our function and made it accept a parameter called filling. filling is a variable, a bucket. It is available anywhere inside the function body, that is between the {curly braces}. It can hold anything, even sandwich filling. We did this when we wrote: let makeSandwich = function(filling).

Further down in our code we call makeSandwich(“marmite”); Here we are passing the string “marmite” to our function. It will be automatically assigned to the variable called filling which will be magically available to our function when it runs.

Exercise - Crab Pate - Mmmmmm

  1. Create an HTML file and linked JavaScript file.
  2. Enter the code above carefully and run it.
  3. Create a Crab Pate sandwich.

Answers

makeSandwich("crab pate");

Butter allergies - Passing Multiple Parameters

Poor Mrs Potts. She’s just remembered that some of the children are allergic to milk. If they eat butter they may go into anaphylactic shock. She needs to make some of her sandwiches with margarine. Things keep getting worse and worse for Mrs Potts, she looks like she might cry. Fortunately, you are here to help her. We can extend our sandwich function to accept two parameters.

let makeSandwich = function (filling, spread) {
  alert("Get bread");
  alert("Spread the " + spread);
  alert("Spread the " + filling);
  alert("Cut off the crusts");
  alert("Put in a little bag");
};

makeSandwich("marmite", "butter");
makeSandwich("jam", "margerine");
makeSandwich("squeezy cheez", "butter");

Now we are passing in two parameters, one called filling and one called spread. Filling comes first, spread comes next. When we call the function, we pass in a filing, then a spread and those values get assigned to the filling and spread variables inside the function body, i.e. everywhere between the {curly braces}.

Exercise - Multiple Parameters

  1. Create an HTML file and linked JavaScript file.
  2. Enter the code above carefully and run it.
  3. Create a tuna and sweetcorn sandwich with artisan linseed margarine. 4. Some of the children need rye bread. Make the function accept another parameter: breadType and make some more sandwiches.

Answers

let makeSandwich = function (filling, spread, breadType) {
  alert("Get" + breadType);
  alert("Spread the " + spread);
  alert("Spread the " + filling);
  alert("Cut off the crusts");
  alert("Put in a little bag");
};

makeSandwich("tuna and sweetcorn", "soya margarine", "rye bread");

Return Values - the Sandwich Machine

So we have created a make sandwich function, and passed it some ingredients. We have control over our function.

At the moment though, all our function does is bung the various stages of the sandwich making process into alert boxes as it goes along. What if we don’t want alert boxes, what if we want to output them to the console instead, or turn them into a web page? Mrs Potts doesn’t like a fuss.

It would be sort of handy if, instead of just alerting the sandwich stages, the makeSandwich function could make the sandwich, then just hand us the completed sandwich back, perhaps as a string, sort of like a sandwich machine. Then we could choose what to do with our sandwich, alert it, add it to a pile of other sandwiches, feed it to a child, etc…

To do this, we need to understand about return values. When we use the return keyword in a function, the value that we ask to be returned is sent back out of the function.

When we use the return keyword in a function, the value that we ask to be returned is sent back out of the function.

Observe:

let makeSandwich = function (filling) {
  return "A sandwich loving made with " + filling;
};

alert(makeSandwich("tofu mayonnaise"));

// A sandwich loving made with tofu mayonnaise

See? Our make sandwich function now makes a sandwich and returns it.

We sometimes call this input, process and output. It’s as though we have made a sandwich machine. we pass it ingredients, it processes them into a sandwich (or a string in this case), and returns it to us.

Note that we can use our sandwich machine anywhere where we might have used a string previously. JavaScript will see the function, execute it, get a string back, and then just act as though there was a string there all along. Our function is an Expression!

Exercise: A trickier sandwich

  1. Enter the code above and get it to run.
  2. Extend it so it takes 2 fillings, perhaps “tuna” and “falafel”.
  3. Instead of using an alert, output the returned sandwich using an alert box.
  4. Instead of alerting directly, save the sandwich in a variable. Now alert the variable. Using sensibly named variables like this can make your code easier to read.

Extra Difficult Bit: involving stuff you haven’t covered yet

Here’s a curve ball for Mrs Potts. Please ignore this bit. Definitely don’t try and do it yet.

We are going to extend our code so that it is possible to pass in either one or two fillings. The function should handle this by only outputting one filling if just one is passed in, or two if two are passed.

To solve this puzzle, we need to use an if statement. We’ll get to these in a while when we cover flow control, but for now just pretend it makes sense.

We can check to see if filling2 is present, and if it is, we can add it to the string.

let makeSandwich = function (filling1, filling2) {
  let sandwich = "A sandwich with " + filling1;
  if (filling2) {
    sandwich += " and " + filling2;
  }
  return sandwich;
};

We can call this like so:

alert(makeSandwich("marmite", "cheese"));
alert(makeSandwich("marmite"));

A handy feature of JavaScript is that if you don’t pass in a parameter, it is set to be undefined. `Undefined“ is a special value that a variable has before anything has been put in it. It’s an empty bucket.

One of the great things about undefined is that it’s falsey. Falsey values evaluate to false, so we can call our makeSandwich function like this:

alert(makeSandwich("butter", "marmite"));

Filling2 is undefined, and so evaluates to false in the if statement. This is a very handy feature of JavaScript.

Notica also how we can drop our function call right into the call to alert. Alert is also a function BTW, in case you hadn’t realised. This is a compound expression. makeSandwich runs and changes to a value, then that value is already between the braces for the alert function.

Maybe sleep on it?

Functions are one of those things that people often find a little mind bending the first time they see them. If this is you, I suggest you put this down and go have a nap, let your brain do it’s thing integrating the new knowledge. You’re doing great!

Now on to Flow Control!

Flow Control - Do this, or else…

Our programs so far have been very nice, but quite linear. We can make sandwiches, but we can’t decide whether or not we should be making sandwiches. Sometimes in our code we need to be able to be respond to things. We need to be able to say “what if?”

Day into Night

We do this using the if statement:

let daytime = true;

if (daytime) {
  alert("Nice day!");
}

In this example, daytime is a variable that contains a special value. The value is true. True means yes, absolutely, do it. The opposite of true is false. False means no, never, don’t do it. The code between the curly braces will only run if daytime is true. It will not run if daytime is false.

Exercise - Night time

  1. Create an HTML file and linked Javascript file.
  2. Enter the code above and run it.
  3. Set the daytime to false and see what happens. Is that what you expected?

Do this, or else

Sometimes we want to do a different thing if we didn’t do the first thing. We need an else statement. Thankfully, this is easy.

let daytime = false;

if (daytime) {
  alert("Nice day!");
} else {
  alert("Nice night!");
}

Here the first block of code is run if daytime is true and the second block is run if daytime is false.

Exercise - if else

  1. Create an HTML file and linked JavaScript file.
  2. Enter the code above and run it.
  3. Set the daytime variable to true and see what happens. Is that what you expected? Do this, or else do this, or else do this or else

Sometimes we need more than 2 options. What if we wanted to say good evening and good morning too. We’re going to need a little more information than just our true/false daytime variable. Let’s create an hour variable to hold the hour of the day.

let morning = true;
let daytime = false;
let nightime = false;

if (morning) {
  alert("Good Morning!");
} else if (daytime) {
  alert("Nice day!");
} else if (nighttime) {
  alert("Nice night!");
} else {
  alert("I just don't know what time it is!");
}

Wow, that was a little longer, but it does seem to make sense. If morning is true it does the first bit of code, else if daytime is true it does the second bit of code, else if nighttime is true it does the third bit. If none of the above are true it does the last bit of code.

Exercise - Free choice

  1. Create an HTML file and linked Javascript file.
  2. Enter the code above and run it.
  3. Set the nighttime variable to true and the daytime variable to false. What happens?
  4. Set all the variables to false, what happens?
  5. Set all the variables to true. What happens? Why?
  6. Add evening and midnight.

Well done! If you’re still following along, you’re doing great! Next we’ll look at the magical world of Booleans!

An exciting foray into Booleans. What Ho!

These values that we’re using, true and false, have a special name. They are called Boolean values, named after the wonderful Victorian English mathematician George Boole who first described them. Boolean values are actually the basis for all computing. You may have heard it said that computers use ones and zeros, and it’s true. Deep inside, computers are made of vast arrays of switches, which can be either on or off, one or zero, true or false.

George Boole

George Boole - He looks like a nice sort of chap, a bit like Colin Firth.

The simple operations we carry out on Boolean values, when combined in clever ways, let a computer do all the clever things it’s able to do. When you move your mouse pointer, there’s a whole cascade of little ones and zeroes bouncing around inside the chips and cables that you will never see.

In the context of JavaScript, Booleans are useful in decision making. Should we do this or that? Should we let the user submit their shopping cart or not. Should this element be clickable or not. Lets have a look at what we can do.

This AND That

One of the simplest things we can do with Booleans is the “and” operation. It looks like this:

let daytime = true;
let sunny = true;

let canGoOut = daytime && sunny;

Here we set a variable called canGoOut. This variable will be true if both daytime and sunny are true.

We can use this in a program like so:

let daytime = true;
let sunny = true;

let canGoOut = daytime && sunny;

if (canGoOut) {
  alert("lets go out!");
}

or more simply:

let daytime = true;
let sunny = true;

if (daytime && sunny) {
  alert("lets go out!");
}

Exercise - this AND that

  1. Create an HTML file and linked Javascript file.
  2. Enter the daytime && sunny code above and run it.
  3. What happens if daytime is not true?
  4. What happens if sunny is not true?
  5. Add an icecreamTruck variable. Only go out if there’s also icecream available. Obviously.

Answers

let daytime = true;
let sunny = true;
let iceCream = true;

if (daytime && sunny && iceCream) {
  alert("lets go out!");
}

This OR That

The second useful thing we can do with Booleans is OR. Sometimes we want to be able to say “do something if this other thing is true, OR if this second other thing is true. We do this in Javascript using two vertical bar character ||. For example:

let iFancyIcecream = false;
let youFancyIcecream = true;
let buyIcecream = iFancyIcecream || youFancyIcecream;

We can use this in a program like this:

let iFancyIcecream = false;
let youFancyIcecream = true;
if (iFancyIcecream || youFancyIcecream) {
  alert("I am just going to the shop now...");
}

This and that or this

You’re getting the idea now, these boolean operators are operators just like any other. As such we can combine them together to make compound expressions:

let cheese = true;
let icecream = true;
let bread = true;
let soda = true;
let littlePotsOfFrenchYoghurt = true;

let iHaveAPicnic =
  (cheese && bread && icecream) || (soda && littlePotsOfFrenchYoghurt);

See? I have a picnic if I have cheese AND bread AND icecream; OR if I have soda AND Petit Filou, or somesuch tomfoolery.

George would probably have approved, he looks the type to enjoy a Petit Filou on a hot day.

Exercise - IceCream

  1. Create an HTML file and linked Javascript file.
  2. Enter the icecream code above and run it.
  3. What happens if I fancy icecream?
  4. What happens if you fancy icecream?
  5. What happens if neither of us fancies icecream?
  6. Add the sunny variable. Only go out if I fancy icecream or you fancy icecream, and it’s sunny. You’ll need to use some braces here.
  7. Add the icecreamTruck variable. Only go out if I fancy icecream or you fancy icecream, and it’s sunny and there’s an icecream truck nearby.

Not That!

Another useful thing we can do with Booleans is Not.

Sometimes we want something to happen if something is not true. For example we might want to display an error if someone has not filled in a field correctly. We say not! in JavaScript using an exclamation mark, like so:

let filledInField = false;
if (!filledInField) {
  alert("Please fill in the field!");
}

NOT changes a true to a false and vice versa. If southing is true, make it false. If something is false, make it true.

Exercise - NOT

  1. Create an HTML file and linked Javascript file.
  2. Enter the not that! code above and run it.
  3. What happens if the field is filled in (the value is true)?

This is something we do a lot in JavaScript, enable buttons on forms when all the values have been entered. It’s useful.

Equals this ===?

So far and so esoteric. It’s all very well setting Boolean values explicitly in our code, but for this to be useful we need to be able to be able to make Booleans from other values. Lets return to our timing example above. Lets say that have a variable called hour, and we want to determine if it’s mid-day or not. We might do something like this:

let hour = 12;
let midday = hour === 12;

alert("hey yo, it's midday");

Here we’re simply saying: if the hour variable is equal to 12, the midday variable is true. In JavaScript === means equal to. That’s right, === is also a boolean operator.

Exercise - Midday

  1. Create an HTML file and linked JavaScript file.
  2. Enter the midday code above and run it.
  3. What is the value of midday?

My dad is bigger > than your dad

We can do other mathematical operations to make Booleans. Here we do one thing if hour > 12 and another if hour is less than 12.

let hour = 13;
if (hour > 12) {
  alert("after midday");
} else {
  alert("before midday");
}

hour > 12 is an expression that evanlutes to either true or false, depending on whether the hour is indeed greater than 12.

We can combine Boolean operators in all kinds of ways, for example:

let hour = 13;
if (hour > 11 && hour < 14) {
  alert("you could have lunch now.");
} else {
  alert("it isn't lunchtime.");
}

Exercise - Build a little clock

  1. Create an HTML file and linked Javascript file.
  2. Enter the code above and run it.
  3. What is the result?
  4. Use else if operators to create a sort of an alert clock that says different things at different times of day.
  5. You can use the following code to get the actual time of day: let hour = (new Date()).getHours();
  6. Hook your clock up to the actual hour of the day. Remember to check back later!

Answers

let hour = new Date().getHours();

if (hour < 7) {
  alert("Too Early!");
} else if (hour === 7) {
  alert("Breakfast");
} else if (hour === 11) {
  alert("Second Breakfast");
} else {
  alert("Fool of a Took!");
}

Further Exercise

  1. Create a myDadSize variable
  2. Create a yourDadSize variable
  3. If my dad is bigger than your dad, alert this fact.
  4. If your dad is bigger than my dad, alert this also.
  5. If both dads are the same size, alert this fact also.

Answers

The best way to tackle this is with an if / else if / else statement. There are 3 possible results, either one dad is bigger than the other, or they are the same.

let myDadSize = 12;
let yourDadSize = 13;
if (myDadSize > yourDadSize) {
  alert("My dad is the biggest (of course).");
} else if (myDadSize < yourDadSize) {
  alert("Oh, your dad is the biggest.");
} else {
  alert("Our dads are the same size");
}

Onwards and ever upwards! Did I mention you’re doing a brilliant job? Next up is Loops!

Froot Loops

So, we’ve learned most of the major things we need to know in order to program. We’re nearly ready to create some cool stuff. There are just a couple more things we need to know before we jump start writing proper programs.

Remember Mrs. Potts and the poor starving children? I wonder what happened with that. Do you think the children were OK? I hope so. We helped Mrs. Potts a lot by giving her a makeSandwich function, but she still needs to call it a lot of times. What if there was an easy way for her to call the makeSandwich function 10 times, 100 times, a million times without writing one more line of code.

Thankfully there is! Enter Loops!

While Loops - Get them while you can!

A while loop in JavaScript is a type of loop that will keep going while some condition is true. For example

let sandwichesMade = 0;

while (sandwichesMade < 5) {
  alert("Making Sandwich: " + sandwichesMade);
  sandwichesMade = sandwichesMade + 1;
}

First we set the number of sandwiches we have made so far:

let sandwichesMade = 0;

Then we say to the Javascript engine

while (sandwichesMade < 5) {
  //do something
}

This is the loop. It will go round until the condition sandwichesMade < 5 is not true any more. WHILE the condition is true, kindly DO the thing between the curlies, then come chanck again and check again.

Inside the loop we have to remember to do this:

sandwichesMade = sandwichesMade + 1;

This increases the value of sandwichesMade. Without this, the loop will go around forever until the page times out or the universe ends.

Exercise - Countdown

  1. Create an html file and linked javascript file.
  2. Enter the code in the previous section.
  3. Run it. What happens?
  4. Try to modify your code to make a javascript countdown. Start at 10 and count down to 0.
  5. Alert the string “Lift Off Mrs Potts!” when the countdown reaches zero.

Answer

let i = 10;

while (i > 0) {
  alert(i);
  i = i - 1;
}

alert("Lift off Mrs Potts");

To tackle this problem, we need a variable to store the current countdown. Here I have called it i. While i is > 0, we continue to execute the code in between the curly braces, reducing the value of i. When i drops below zero, the loop exits and the lift off line is run.

When the loop finishes, the program continues to the next line and we alert “Lift off Mrs Potts”!

Exercise - Looping function

  1. Create an html file and linked javascript file.
  2. Write a function called countdown that accepts a number parameter.
  3. When you call the function, it should alert the numbers down to zero, starting at the number passed to it.

Answers

let countdown = function (i) {
  while (i > 0) {
    alert(i);
    i = i - 1;
  }
};

countdown(35);

Exercise - infinite loop

Try to write code that counts from zero to infinity, never stopping. You need a condition that always evaluates to true. Hmmm, what is always true?

Answer

let i = 0;

while (true) {
  alert(i);
  i = i + 1;
}

Notice while true. A while loop will keep looping over the code in between the braces while the condition is true. True is always true (by definition) so it’ll keep going forever.

For Loops - for he’s a jolly good fellow

The next type of loop we need to know is the for loop. This type of loop is similar to the while loop, but we roll all the various different parts of it up into one line, like so:

for (let sandwichesMade = 0; sandwichesMade < 5; sandwichesMade++) {
  alert("Making Sandwich: " + sandwichesMade);
}

This loop says:

  • sandwichesMade starts at 0.
  • The loop continues as long as sandwichesMade < 5.
  • At the end of each loop increase sandwichesMade by one.
sandwichesMade++;

is just shorthand for add one to the sandwichesMade variable.

This type of loop wraps up a common looping pattern where we create a variable, check to see if the loop should continue executing, and modify the variable.

Questions

  1. Create an html file and linked javascript file.
  2. Enter the code above.
  3. Run it. What happens?
  4. Try to make 20 sandwiches.
  5. Change the code to make sandwichesMade start from 10 and count down to zero.

Answer

for (let sandwichesMade = 10; sandwichesMade > 0; sandwichesMade--) {
  alert("Making Sandwich: " + sandwichesMade);
}

Well done, you’re doing really nicely! In the next section we’ll look at Arrays and Functional Loops, then Objects, and that’s it, those are all the fundamentals of Code!

Arrays

Mrs Potts is in trouble. She has been given the job of making Pizza’s for the staff room Pizza Party. The head wants cheese and tomato, but the deputy head wants 5 cheese, pepperoni, mushroom and ham. How can she represent all these ingredients in a JavaScript friendly fashion? It’s keeping her awake at night.

Thankfully, we can rescue Mrs Potts using Arrays. If a variable is like a bucket, an array is like a rack of buckets, each with a label on it. We can add as many buckets to the rack as we like, and we can put any labels we like on the buckets.

Making an Array

The simplest way to make an array is to declare it, like so:

const toppings = [];

We use square brackets to define an array. This is an empty array.

Putting things into an array

If we like we can put some things in it:

const toppings = [“ham”, “cheese”, “parmesan”] We now have an array containing 3 ingredients. It’s a rack of 3 buckets.

Finding things in an array

Because we haven’t declared any bucket names, Javascript has done it for us by giving each bucket a number. This is subtly different to other languages, do take note.

Let’s take pull out a bucket:

const toppings = ["ham", "cheese", "parmesan"];
alert(toppings[1]);

This will alert the string “cheese”. If we want “ham”, we need the zeroth bucket, like so:

alert(toppings[0]);

This is called zero indexing. The first element is always zero. This actually totally makes sense if you think about it.

Making Buckets

What if we want to store something at a particular point. Let’s do this now:

const toppings = ["ham", "cheese", "parmesan"];
toppings[3] = "little tiny cherry tomatoes";

Here we have put another value in toppings, this time in bucket number 3.

We can verify that our array is now longer using `toppings.length“. The dot operator is to do with object orientation, which we will cover later.

alert(toppings.length);

…will output the number 4.

Arrays in JavaScript are a little bit different

JavaScript arrays are different to arrays in most languages. In most languages, array elements are pointed to by a number. In JavaScript, you are free to use a number to point to an element in an array, but you can equally use a string, or a really big number. You’re encouraged never to do this, but you can.

Arrays in JavaScript are actually same the datatype that many other languages call a hash table, with numbers for keys.

More on this in the JavaScript for Programmers course.

Iterating over an array

One of the most common things you will want to do with an array is to do something with each of its values. We can use a for loop for this.

const toppings = ["ham", "cheese", "parmesan"];
for (i = 0; i < toppings.length; i++) {
  alert(toppings[i]);
}

Here we loop over each numbered bucket and output it’s value. Note that this only works with sequentially ordered buckets.

Exercise - Arrays

If a variable is like a cup, an array is like a whole rack of cups.

  1. Create a function that receives array of pizza toppings. Use a for loop to loop over the array and alert each of the toppings in turn.
  2. Change your code so that instead of alerting the toppings, they are appended to a string. You’ll need to create a string first outside the loop.
  3. Wrap your code up into a sandwich machine that accepts an array of toppings and returns a string representing the pizza.

For in

The other common way to iterate over an array is using a for in loop, like so:

for (let i = 0; i < toppings.length; i++) {
  alert(toppings[i]);
}

Because this is something we do a lot, we have a friendlier way to write this, like so:

for (let i in toppings) {
  alert(toppings[i]);
}

This works if our arrays are not sequential, so for example:

const toppings = [];
toppings[10] = "ham";
toppings[45] = "cheese";

for (let i in toppings) {
  alert(toppings[i]);
}

Exercise - Now to help Mrs Potts

That’s all very well and good, but what about poor Mrs Potts? Let’s write some code that will let her make pizzas with any number of toppings.

  1. Write a make_pizza function that accepts an array of toppings.
  2. Put a loop in your function that loops over the toppings and makes a string to represent the pizza.
  3. Have your function return the string.

Answers

You should have correctly identified that we needed a loop. Here I am using a for loop. I’ve added a little extra code to add ampersands between the toppings.

let make_pizza = function (toppings) {
  let pizza = "";
  for (i = 0; i < toppings.length; i++) {
    pizza = pizza + toppings[i] + " ";
    if (i < toppings.length - 1) {
      pizza += "& ";
    }
  }
  pizza += "pizza";
  return pizza;
};
alert(make_pizza(["ham", "cheese", "parmesan"]));

What do we use arrays for?

In real world coding we use arrays ALL THE TIME!

Arrays are lists. Say you’re making a shopping cart, that’s an list of items. Say you have a menu, that’s a list of links. Say you have a gaming PC, that has an list of parts. Say you have a game. You’ll likely have an array of enemies, an inventory, which is an array of things you found, maybe there are bullets, which you’ll need to store in a list somewhere.

If variables are buckets, arrays are racks of buckets that you access with a number between square braces. Use them whenever you have a bunch of things.

Functional Loops - the power of functions meets the scale of arrays

I’ve told you a little lie, well more of a half truth. I introduced you to loops using while and for, but the reality is we hardly ever use these types of loop anymore outside of toys.

Most of the time, when we loop, we’re looping over an array, like this:

let animals = ["cats", "dogs", "cheeses"];

Now think of our for loop

for (let i = 0; i < animals; i++) {
  alert(animals[i]);
}

What’s wrong with this? One word: encapsulation. Encapsulation means that a thing has everything it needs.

A string knows how to reverse itself:

"hello".reverse();

Because the string is an object. It has a reverse method.

Wouldn’t it make sense if an array knew how to loop over itself? Right now the for loop is on the outside looking in. What if the loop was on the inside of the array, and we told it how to behave? Imagine if we could pass in a little ball of reusable, movable code, right into our array.

What’s a little ball of reusable, movable code called in JavaScript? That’s right, it’s a function.

forEach

Remember how we can assign functions to variables? We can treat them just like any other bit of data. JavaScript is totally cool with this, in fact it likes it.

Here’s a function that can alert a value.

let doAlert = function (value) {
  alert(value);
};

The astute among you will notice this function is completely superfluous, since alert is already a function, but I’m going to press on because I’ve already typed the example.

now I can call:

animals.forEach(doAlert);

Just that. Mind bending right? You might need to sleep on this one. I passed the doAlert function to the forEach method of the array. This method will call the function once for each element in the array, passing in that element.

I’ll say it again: forEach will call the doAlert method once for each element in the array, passing that element to the doAlert function!

Maybe read that a couple of times until it makes sense.

And this is encapsulation. See how tidy it is?

map

We have lots of funcitonal looping strategies. Map is a good one, it will accept a function, then call that function once for each element in the array, and output a new array where the values are the return values from the function.

I’ll say that again: Map will accept a function, then call that function once for each element in the array, and return a new array where the values are the return values from the function.

Gosh. Maybe an example? Don’t worry, this is easy once you get it, and rally getting it takes most people at leaset a couple of days.

Heres a funciton that accepts a string and returns a new string suitable for Mrs Potts.

let toSandwich = function (filling) {
  return "a sandwich made with " + filling;
};

now let’s pass it to map:

const sandwices = animals.map(toSandwich);

and what do we get?

[
  "a sandwich made with cats",
  "a sandwich made with dogs",
  "a sandwich made with cheeses",
];

Wow! That sounds maybe like it might be useful. This morning I worked on a trading platform for a major bank. I had a list of stock tickers and I wanted to have a list of DOM nodes on a web page. Guess what I did? That’s right, I used a map!

Whenever you need to transform a list of one type of thing into a list of the same length of another type of thing, use a map.

Other functional loops

  • forEach calls a function for each element, and passed that element to the function
  • map does the same, but bungs the return value back in a new array
  • reduce builds a new value that gets passed back into the function over and over. Master this one and you’re officially a wizard, or possibly a wizrobe. Exercise for the reader.
  • filter accepts a function that returns true or false. It loops over the array and returns a new array which only contains the values for which the function returned true
  • find as above, except it only returns the first value it finds. Nice

And there we go. Amazingly useful, fully encapsulated. Kinda brain-breaking? Let it sit awhile, I believe in you, you’ve got this.

Objects - Like Folders on your Desktop

My wife keeps all her files on her desktop. To me, this looks messy, but for her it’s actually pretty good organisation because she doesn’t use her computer very often, so it’s handy for her to have everything right there at the top level. There’s not that much stuff.

I keep all my files in a series of nested folders. I do this because I have WAY more files. Being a coder, I’ve probably got close to a million files in my home directory. so I need to be more organised.

Objects are like folders

Think of the programs we’ve made so far. We’ve created a bunch of variables, and Mrs Potts was pleased, but these programs were small. What if we needed a couple of thousand variables, even a couple of million. In a modern game you might be tracking literally billions of parameters. We need an organisation tool.

Objects fill this role nicely

In JavaScript we have two main ways of staying organised:

  • Object Orientation - which lets us create little balls of variables
  • Functional code - which lets us create variables that are local to functions, then nest functions inside each other

In this section we will be looking at object orientation

Creating objects

In some languages, creating objects is work. In JavaScript it is easy.

Create an object like this:

let myCat = {};

I just made an object called myCat. Nice.

Cats have attributes. They have legs, whiskers and a tail. I can represent this like so:

let myCat = {
  legs: 4,
  whiskers: 1000,
  tail: 1,
};

Without an object, I would have to create a bunch of separate variables. Now I have them all nicely balled up in a single variable called myCat. I can pass myCat around, and all its attributes will pass around with it.

Attributes vs. Variables

  • When we put something in an object we call it an attribute of that object.
  • When we create a new variable using let, const or var, that’s a variable.

This may seem like a subtle distinction, but it’s an important one that runs deep into the language. Attributes and variables behave differently and have a different implementation.

Attributes are not variables. They’re actually string keys in a HashMap. Don’t worry if this doesn’t make sense yet, we’ll come back to it in the advanced course.

Putting it all together

We’ve now learned pretty much all the fundamentals of JavaScript. You should now be equipped to write some simple programs. Here are a couple you can try. Think of these as Kata, you may find them easy or you may find them surprisingly hard. Either way, persist. Solving actual problems is what makes this stuff stick.

Exercise - A Sandwich Calculator

You’ll need a function, an if statement, and some maths to handle this. The function needs to accept parameters and return a calculated value. Good luck!

  1. Write a function called sandwich calculator. This should accept one value: slicesOfBread
  2. The function should return the total number of possible sandwiches based on the amount of slices available, so if there are 10 slices, it should return 5. Test your function with an alert box.
  3. Extend your function so it accepts two values, slicesOfBread and slicesOfCheese.
  4. It takes two slices of bread and one of cheese to make a sandwich. The function should return the total number of possible sandwiches, so if there are 10 slices of bread, but only 1 of cheese, it should return 1. You’ll need an if statement to make this work.

Sounds dumb? This morning I worked on a trading platform for a major bank. They wanted to disable the submit button if a set of complex criteria were not met. I used a function and some maths, then set that as the disabled attribute of a button. It’s the same thing.

Exercise - An Array of Sandwiches

In this one you’ll need a loop. I’ll leave the choice up to you. You’ll need a function that accepts an array, and a bunch of alerts.

Here is an array of requests:

var filling_requests = ["ham", "cheese and cucumber", "humous and mayo"];
  1. Write a function that accepts an array of requests and alerts the sandwich it is making. You’ll need to iterate over the array.
  2. Extend your function so that it returns an array or sandwiches, like this:
["ham sandwich", "cheese and cucumber sandwich", "humous and mayo sandwich"];

Ridiculous right? This afternoon I worked on passing a set of commodities through to an app as an array, then rendered them in a dropdown. Same deal, just not sandwiches.

On the next page you’ll find some even harder problems as we build out a silly little game.

Object Orientation with Mario and Luigi Exercise

In this section we’re going to create a dumb little game using objects. This will be an object oriented game.

Remember that JavaScript objects looks like this:

```js
let mario = {
  description: "Small and jumpy. Likes princesses.",
  height: 10,
  weight: 3,
  speed: 12,
};

let bowser = {
  description: "Big and green, Hates princesses.",
  height: 16,
  weight: 6,
  speed: 4,
};

Here we have defined two objects, one called mario and on called bowser. As you can see, they consist of a series of name value pairs. We can access the values like so:

alert(mario.description);

We can modify values like so:

mario.description = "Big and smashy, having eaten a mushroom";

We can even add new attributes like so:

mario.canFly = true;

Objects are useful for keeping things neat and tidy. We have encapsulated all the information about Mario in a single place so it’s easy to get at and understand.

Exercise - canFly

  1. Enter the above code
  2. Alert the values of mario.description and bowser.description```
  3. Use your web inspector to add a breakpoint. Check the values of the JSON objects in the debugger.
  4. Add a canFly attribute to Mario using the dot syntax. Again, check the debugger.
  5. Create an entry for Luigi. He’s a bit thinner that Mario, but slightly taller, and he wears a green outfit.

A Rather Dull Mario Game

If we wanted we could write a little Mario game using these objects. Lets create a little function to see who wins in a boss battle:

```js
let bossBattle = function () {
  if (mario.speed > bowser.speed) {
    alert("Mario has escaped and saved Peach");
  } else {
    alert("Bowser has stomped all over Mario. Mario is dead.");
  }
};
bossBattle();

As we can see, Mario wins. Let’s swing the odds a little in Bowser’s favour. Bowser can go into a powered up mode where he swoops from side to side on the screen. We’ll call this Bowser Boost.

Let’s extend our game a little to add Bowser Boost:

let mario = {
  description: "Small and jumpy. Likes princesses.",
  height: 10,
  weight: 3,
  speed: 12,
};

let bowser = {
  description: "Big and green, Hates princesses.",
  height: 16,
  weight: 6,
  speed: 4,
  boost: 0,
};

let bossBattle = function () {
  if (mario.speed > bowser.speed + bowser.boost) {
    alert("Mario has escaped");
  } else {
    alert("Bowser has stomped all over Mario");
  }
};

bossBattle();
bowser.boost = 20;
bossBattle();

Exercise Invincible

  1. Enter the above code and get it to run. Who wins?
  2. Give Mario an invincibility attribute. If invincibility is true, Mario always wins. Unfair I know.
  3. Don’t worry, we are going somewhere with this. Next!

Lets clean this code up a little

  1. Add two more attributes to each character: attackPower and name.
  2. Extend the boss battle function so it receives two parameters, contestant1 and contestant2.
  3. Rewrite it so that instead of running the conditional, it simply prints out the name of the contestant with the highest attackPower. This renders all the other attributes irrelevant, it only checks the attackPower.

Functions within Objects - Methods

This is all very well. We have Mario and Bowser objects and a function to compare them, but it seems a little artificial having all our functions scattered all over the place like this. Also, the more functions we have in our global namespace, the more likely it is that they will conflict, and we’ll accidentally overwrite something important.

Let’s see if we can improve things.

let marioWorld = {
  mario: {
    name: "Mario",
    description: "Small and jumpy. Likes princesses.",
    celebration: "Mario wins and does a tidy little dance. Jiggy",
    height: 10,
    weight: 3,
    speed: 12,
    attackPower: function () {
      return this.weight * this.speed;
    },
  },

  bowser: {
    name: "Bowser",
    description: "Big and green, Hates princesses.",
    celebration: "Bowser wins and does a big hairy kind of roar",
    height: 16,
    weight: 6,
    speed: 4,
    boost: 0,
    attackPower: function () {
      return this.weight * (this.speed + this.boost);
    },
  },

  bossBattle: function (contestant1, contestant2) {
    alert(contestant1.name + " vs " + contestant2.name);
    if (contestant1.attackPower() > contestant2.attackPower()) {
      alert(contestant1.celebration);
    } else {
      alert(contestant2.celebration);
    }
  },
};

marioWorld.bossBattle(marioWorld.mario, marioWorld.bowser);

Ah, that’s better. As you can see, this entire program is encapsulated within a single object called marioWorld. The marioWorld object is the only object in the global namespace. the bossBattle function is now an attribute of marioWorld, and each contestant has an attackPower function that works out his strength in a battle. The bossBattle function is parameterised, so you can battle any contestant against any other.

We have also written an attackPower function which is implemented by bowser and mario. This calculates the attack power from a series of other parameters.

Because functions are objects, we can assign them as attributes of objects. They’re key value pairs, but if you’ve programmed before, you’ll notice they work like methods. We can now call methods on our JSON objects.

What is this?

You might have noticed also that in the attackPower function we use the “this” keyword. We say this.speed and this.boost.

This is a troublesome keyword that trips up even quite advanced JavaScript developers all the time. ”this” refers to the context in which the code is currently operating in. In this case, the context is mario (or bowser) and so this refers to these variables. That’s because the attackPower function is an attribute of mario. This points to the object the current object is a member of. Your knowledge of JavaScript will one day be measured by your understanding of scope, and the ”this” keyword, so we’ll come back to this in the advanced course, but for now, let’s make a real game…

Exercise - Princess Peach

  1. Enter the above code and make it work.
  2. Add Princess Peach. The princess is smaller and lighter but compensates for this by being quicker and having a dash mode. Battle Peach vs Bowser and Peach vs Mario.
  3. Add an activateBoost function to Bowser that adds 5 to his boost. You should be able to call marioWorld.bowser.activateBoost.
  4. Add a toggleDash function to peach. Calling it should activate or deactivate her dash attribute.
  5. Just for kicks, change the boss battle function so instead of outputting alerts, it returns a string. Now we have an API. Display that string where you call bossBattle
  6. Add a function for Bowser Boost. When you run it, his boost is increased.
  7. Add a Peach Dash toggle. Every time you run it, Peach’s dash mode is toggled on and off.

And there we go. That’s it. If you’ve stuck with the program this far, amazing! You now know all the fundamental pieces of code. Seems like a lot? Seems like not so much? Both things can be true.

You should now have a good understanding of:

  • strings
  • variables
  • numbers
  • operators
  • expressions
  • booleans
  • functions
  • if / else
  • loops
  • arrays
  • functional loops (aka - welcome to functional programming!)
  • objects (aka - welcome to Object Oriented Programming)

And that’s pretty much all there is.

Code is like hobbits, You can learn all it’s ways in a few hours, and then the rest is learning how to fit it together, and this is when the real work begins.

Bonus Section - A Dash of JQuery

You’ve made it, now lets make it fly…

For the most part, when we write JavaScript, we want to use it to talk to and modify web pages. We do this via a thing called the Document Object Model or DOM - a series of JavaScript objects that let us interact with every part of the page.

Think of the web page as a set of nested elements, paragraphs inside divs inside articles. Each of these can be represented as an Object. This is why we call it the Document Object Model.

When it was new, the DOM was put together in a bit of a hurry and was not very easy to use. Douglas Crockford once described it as “The worst API ever conceived of”. It has got a lot better over the past few years, but most of us still use some kind of wrapper to make using it easier.

Wrappers include React, Vue and Angular - which will automatically bind the DOM to changes in data.

And then we have JQuery. JQuery is used by roughly 50% of all websites. It is incredibly simple to pick up. Some people think we should abandon JQuery, but honestly, I think this is pulling up the ladder. JQuery is super simple to get started with, and it will teach you concepts such as navigating the DOM tree and event handling. Some people build their whole careers around it, others use it as a stepping stone. Either way, it makes for a good entry point into the DOM, and that’s what we’ll be using it for here.

Hello JQuery!

So lets jump right in! First we need to download a copy of jQuery, so go visit jquery.com and download the latest version. I’ve got version 1.8 here in front of me now, but you’ll probably get a newer version that this. You’ll be offered the choice between a regular or minified version. Choose the regular version for now.

The HTML

Now we need to create an html file for our scripts to live inside. Enter something like the following:

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery</title>
    <script src="jquery.js"></script>
    <script src="hello.js"></script>
  </head>
  <body></body>
</html>

Note that the body element is empty.

The Javascript

Next we’ll need to create the hello.js file, so go ahead and create it and add the following text:

$(function () {
  $("body").html("Hello jQuery");
});

Whoah, that looked complicated! Don’t worry though, there’s actually nothing here that we haven’t already covered. We’ll break this down in a minute, but for now let’s just type it in and have a look.

JQuery Hello World Exercise

  1. Create the program above and run it. What do you see?
  2. Modify the program to make it say a different greeting.

Decomposing hello world

The code we entered just now might look strange, but actually it’s quite simple. JQuery works by defining a single function called .Why. Why ? Because $ easy to type and has no other meaning in JavaScript. Here is our Hello jQuery script again.

$(function () {
  $("body").html("Hello jQuery");
});

Notice that it is wrapped in the dollar function like this:

$( ...code goes here...);

Now it makes more sense, we have a function called $ (dollar) which accepts an argument. Remember in the last section we looked at functions, we said that a function could be assigned to a variable? That’s because, in Javascript functions are Objects. We can pass them around, do things with them, assign them to variables, etc, etc.

In this case the dollar function is accepting another function as an argument. The function it’s accepting looks like this:

function() {
$("body").html("Hello jQuery");
}

This is an anonymous function, it doesn’t have a name, but it’s a function none the less. Lets look inside it:

$("body").html("Hello jQuery");

This looks simpler. We’re calling the functionagain,butthistimewerepassingitastring"body".Whenthe function again, but this time we're passing it a string "body". When the `` function receives a string, it uses it to find an element on the page. Horray, it has found the body element!

JQuery adds a bunch of convenience methods to any element it returns including this one .html(). The html method lets us set the html content of an element, so here we’ve set the content to the string "Hello jQuery".

Passing $ a function

One mystery remains, why did we have to pass our code to $ as a function? Why wrap all that stuff up inside a function at all?

Well…

The dollar function behaves differently depending on what you pass it. If you pass it a string it finds the element that matches that string. If you pass it a function, it remembers that function and calls it as soon as the DOM is ready, that is, as soon as your page has downloaded. So by wrapping our code up in a function and passing it to jQuery first thing, we guarantee that jQuery won’t try to run our code until our HTML is completely loaded. It’s listening for the onLoad event on the whole page.

Let’s look at it another way…

jQuery - a conversation.

You: Hi jQuery, I’ve written some code. Here’s a function for you. I’ll pass it to you using your $ function. I know you like that..

jQuery: Thanks User, I’ll execute that function just as soon as the page html has finished loading and the DOM is ready. I’m clever and I know just when that will be for all the various different browsers.

…time passes…

jQuery: Ah, the DOM is ready, lets look at that function. Little Function? You can run now!

Little Function: Hello there jQuery, nice to be running at last. jQuery, can you find me the body element?

jQuery: Of course I can, with pleasure! Here it is, and I’ve taken the liberty of decorating it with a bunch of useful utility methods for you.

Little Function: Great, I’ll call the html method to set the html of the body element you gave me on the DOM.

DOM: Aha, oho, you’ve set the inner html of the body element. I’ll just tell the browser.

Browser: Thanks DOM. What’s that you say? You’ve been updated? I’d better redraw myself. There, that’s all done.

…more time passes…

You (completely unaware that any time has passed at all): Horray. My page now contains the text I wanted!

jQuery Selectors

In the example above, we used jQuery to set the html of the body element. We selected the body element, then called the html method on it.

We can use jQuery to select any element on the page. We do this using CSS syntax. Lets say we wanted to select all the paragraphs on the page, we would do this like so:

$("p");

Lets say we wanted the hyperlink with class name “login”:

$("a.login");

The string is just CSS. Any CSS will do, even the really edge stuff.

Exercise

  1. Create an html document containing several hyperlinks, some of which have class attributes.
  2. Link the jQuery library and a blank script file of your own.
  3. Set the html of each hyperlink to “Hello from the hyperlink!”, or some other text of your choosing.
  4. Pick a couple of hyperlinks with classes. Use CSS syntax in your selector to give them different html content.

Are you starting to see how you might use JavaScript to create a whole web page? This is what we call a WebApp. People pay good money for Webapps.

More on CSS Selectors.

Because jQuery uses CSS to select elements, plus it’s own extensions, you can use jQuery to pull out and make changes to pretty much anything on the page. It works in all browsers so you don’t need to worry about browser inconsistencies.

Read http://api.jquery.com/category/selectors for a full up to date list of selectors. It’s a long and useful list.

jQuery Events - listen to me and do what I say!

The real strength of JavaScript is that it allows the page to respond to the user. Whenever the user does something on the page, from moving the mouse to pressing a button, to submitting a form, lots of little events are fired off in the browser. We can tell our code to listen for certain events and call functions in response to them.

Events Exercise

  1. Create an HTML file and import jQuery.
  2. Create a file called dont_click.js and import that too.
  3. Edit your html file so it looks like this:
<!DOCTYPE html>
<html>
  <head>
    <title>jQuery</title>
    <script src="jquery-1.5.js"></script>
    <script src="dont_click.js"></script>
  </head>
  <body>
    <div class="clickable">Do not press this button.</div>
  </body>
</html>
  1. Enter the following JavaScript into your dont_click.js file.
$(function () {
  $(".clickable").click(function () {
    alert("I can't believe you just did that!");
  });
});
  1. Reload your page and don’t click the text!

Deconstructing don’t click

How was that? Tricky? Make sense? Did you click the text? That’s super rude, I asked you nicely not to.

Let’s just deconstruct the JavaScript a little and have a look inside.

First we have this:

$(function() {
    ...
});

This calls the dollar function and passes it a function. When we pass dollar a function, jQuery puts it on one side until the DOM is loaded and runs it then.

The function we passed it looks like this:

$(".clickable").click(function() {
   ...
});

Can you guess what it does? First it gets all the elements on the page with class “clickable”. Then it calls a method called click on them. This method says what to do when we click. It’s a click handler.

And what happens when we click it? This happens:

alert("I can't believe you just did that!");

…and we get our cute little alert box. So appealing!

Exercise - More event handlers

  1. Review the list of events on: http://api.jquery.com/category/events/
  2. Try to write some code that pops up an alert when the user double clicks the button.
  3. Try to write some code that pops up an alert when the user mouses over the button.
  4. Try to write code that removes the button from the body when the user mouses over it. (hint: set the body html to an empty string "")

jQuery Forms - Talk to me…

OK, it’s not sexy, but sooner or later we’re going to have to cover it. Forms. There, I’ve said it. Don’t worry, next well be looking at animation so lets just take a deep breath and…

Make a form:

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery</title>
    <script src="jquery-1.5.js"></script>
    <script src="form.js"></script>
  </head>
  <body>
    <form>
      <label for="gadget">Please enter a handy gadget, eg jet boots.</label>
      <input type="text" id="gadget" />
      <input type="submit" value="Go Go Gadget jQuery!" />
    </form>
  </body>
</html>

This simple form doesn’t do much. Let’s make something happen with some…

Go Go Gadget JavaScript!

$(function () {
  $("form").submit(function () {
    var gadget = $("#gadget").val();
    alert("Go Go Gadget " + gadget);
    return false;
  });
});

As you’d expect, jQuery lets us look at the values of form elements. It does this using the val method on any form element. As you can see above, we’re responding to the submit event with a function that writes an alert to the screen.

Exercise - with forms

  1. Create the above Form. Yada yada (yawn)….
  2. Give it a spin.
  3. Change the program so that rather than popping up an alert, it puts the go go gadget string into a div.
  4. Extend the program so that you every time you click submit it adds a list item containing the string to an unordered list on the page.

We can do lots of things with forms.

Further Exercise

  1. Create an html file with linked jQuery and JavaScript file
  2. Add two form elements which should accept numbers.
  3. When the form is submitted, add the two numbers together and put the result on the screen.
  4. Add a dropdown containing functions for + and -. When the user clicks submit, call a function that does the appropriate action.

jQuery Effects - Making it zippy

As promised, here we are in the animation section, and what a section it is! jQuery provides a rich and detailed animation library. There are lots of built in effects, or we can define our own, transitioning between pretty much any CSS property you care to mention.

Lets look at some examples

Before we get stuck in, lets look at some examples.

First of all, let’s look at some examples, so head on over to:

…and have a look at some of the demos there. They should give you an idea of what can be done.

I’m a Ninja, watch me fade

For this example we’re going to look at the fadeIn effect. This is a nice effect for revealing things in a smooth way.

The HTML

There’s a fair amount of inline CSS here. If you want to do this properly do please extract this into a separate CSS file, I’m just doing it this way for brevity and clarity.

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery</title>
    <script src="jquery-1.5.js"></script>
    <script src="fade_in.js"></script>
  </head>
  <body>
    <div
      class="hi"
      style="display:none; width:200px; height:200px; background:red;"
    >
      Hi There, I'm a ninja.
    </div>
  </body>
</html>

The Javascript

$(function () {
  $(".hi").fadeIn(1000);
});

As you can see, when the DOM is ready the hi div is faded in.

Exercise - Fade

  1. Enter the code above. Try to get the div to fade in slowly.
  2. What happens if you change the number.
  3. Try using a slidedown animation instead.
  4. Now use a show animation.
  5. If you feel up to it, check out the jQuery animation API on the jQuery website and try to get some other effects running.
  6. If you’re still up for it, check out the effects on jQuery UI. You’ll need to download the jQuery UI library. Horray! Animation!

Other things we can do with jQuery

There’s lots more we can do with Javascript. We can get and set attributes using the attr method. We can add and remove classes using the addClass and removeClass methods. We can set CSS styling using the css method. It all fits inside the same basic framework and I encourage you to try things out.