Coding for Beginners

These notes are for the Northern Beaches Community College "Coding for Beginner" course. If you'd like to skip to a particular section you can enter the section number at the bottom of the page at any time.

Solutions are now avaiable by clicking the appropriate link at the beginning of each example section.

1 - Introduction

What is coding?

Coding, or programming, is writing instructions to a computer in a language it understands. Like this.


Why is coding important?

Knowing how to code will allow you to have computers do essentially anything you want them to.

  • Encourages logical thinking/reasoning
  • Once you learn one language you know them all!
  • Automate processes in your business
  • Develop mobile applications / websites
  • Create thinking computers
  • Simulate real life situtations
  • Automatically play Pokemon GO
  • .............................

2 - Class Summary

Main Topics

  • Google Chrome Developer Mode
  • JavaScript Coding
  • Web Development (HTML5/CSS3)

Coding Topics

  • Numbers
  • Strings
  • Basic Logic
  • Variables
  • Booleans
  • Arrays
  • If statements
  • Comments
  • Else Statements
  • Else If Statements
  • Functions
  • Functions with Inputs
  • For Loops

Web Development Topics

  • Basic HTML
  • Basic CSS
  • Inputs
  • ID's and Classes
  • JavaScript Integration

Why JavaScript?

There are thousands of different programming languages. Most of the languages are specific to particular softwares which have been designed for specific purposes. There are still hundreds of general langauges which anyone can use to do anything. In particular JavaScript is a language which is used in EVERY web browser, on EVERY device in the world. It is without doubt the most used language in the world and because of this it can be much simpler to learn.

3 - Introduction to Google Chrome Developer Mode

Inspect

If you right click anywhere on a website loaded in Google Chrome you'll see "Inspect". What this does is open up the Google Chrome Developer Console and focuses on the code behind what you clicked on. If someone is trying to hack into a website this is usually their first step.

Example:

Enter a FAKE password below, then right click it, click inspect, then change type="password" to type="text".

Elements

Like you saw above, elements shows you all the code behind the website. The language of the code you see is mainly HTML. HTML is the language which is used to layout a page, splitting it into lots of sections. You'll also see some CSS within the HTML. CSS is used to make the page look nice, you can control colours, font sizes etc.

If you wanted do, you could edit any website in any way that you want to, you could even make Facebook say Danbook.

Exercise:

Use Inspect/Element to change my name to yours.

Daniel

Console

This is the tab we will be mainly using. This is where all the JavaScript coding goes. Usually JavaScript is used to control how websites look, making them more interactive. We will be using JavaScript to learn how to code. To write JavaScript to Google Chrome and control your computer, all you need to do is type to the right of the >.

Exercise:

Write alert("Hello") into the JavaScript console.

Other Important Tabs

  • Sources shows you all the files the website depends on.
  • Network shows all the message the website is sending from your PC.
  • Resources shows you all the cookies, databases and files the website has stored on your PC.

4 - Mathematics

Numbers

Every single programming language understands numbers in the same way. All you need to do is enter them as you would in any other situtation.

Exercise:

Enter some numbers into the JavaScript console.

Notice: The computer responds with the same number you enter. We have not told Google Chrome to do anything with the number 10, by default it responds by returning the number back to you. This is called the Output.

Addition and Subtraction

We can have Google Chrome do some math for us, all we need to do is enter it into the console. What is important here is the order which Google Chrome will do the calculations. There are a set of mathematical rules in which everybody and thing must abide by. In particular, anything inside of brackets will be calculated first.

Example:

(1 + 2) - 2 = 3 - 2 = 1

Exercise:

Do some addition and subtraction in the JavaScript console. Try including brackets (1 + 2) - 2.

Multiplication and Division

Multiplication and Division are a little trickier. The main reason is because the symbols we will need to use are less familiar than + and -. On top of this, some languages use different symbols for multilpication and division, be careful. In JavaScript you can multiply numbers using * and divide numbers using /. Just like addition and subtraction there are a set of mathematical rules which need to be taken into consideration. First the computer will calculate everything inside brackets, then it will do multiplication and division, and finally it will add and subtract. You need to keep this in mind when writing mathematics in a programming language. It is also important to know that the computer will do the calculation from left to right, it is important to use brackets when necessary.

Exercise:

Enter the below individually into the JavaScript console.

  • 2*3+4
  • 2*(3+4)
    Notice: The two answers are different. The computer did multiplication before addition, but brackets before multiplication.
  • 10000*8498*9877*61206741
  • 25/5
  • 26546/1654
  • 36*26546/1654
  • 36*26546/1654*2
    Notice: The computer calculated 36*26546/1654 then multiplied it by 2.
  • 36*26546/(1654*2)
    Notice: The computer calculated 36*26546 then divided it by 1654*2.

Is that it?

This is just the start, the above rules are fundamental to every single device in the world. Build upon these fundamentals are solutions to the most complicated problems in the world. But before we get to anything more practical we need to continue learning some more basics.

5 - Words and Sentences

Strings

Words and sentences are referred to as Strings in the programming world. A String can be any combination of any character, including numbers. Because of this, there needs to be a way to tell the computer that we're about to give it a word, phrase or random combination of characters. The computer needs to be able to differentiate our String from numbers and other computational objects so it can know what set of rules it's allowed to use on it. In JavaScript the way you write a String is by wrapping your text with either ' or ". The first quotation we write tells the computer we are about to start writing a String, and the last quotation tells it we're finished. The computer takes all the characters in between and treats them as a string, rather than a number or anything else.

Exercise:

Enter the below individually into the JavaScript console or try your own.

  • "MyString"
    Notice: Just like with numbers, Google Chrome is programmed to return the string after you hit enter, but this time it's in red.
  • "My String"
  • 'My String!2834124($@#*9924'
    Notice: This String has numbers in it, the computer didn't treat it as a number.

Merging Strings

There are a whole range of things we can do with strings. The most simple thing we can do is join them together, or mix them with numbers. Later on we'll do some more complicated things with strings. Merging two strings together is similar to adding two numbers, you write the two strings you want next to each other, with separate sets of quotations, then put a + between them.

Exercise:

Enter the below individually into the JavaScript console or try your own.

  • "MyString"+" "+"Another String"
  • "My String"+" "+'Another String'
    Notice: You can add strings with single quotes to ones with doubles.
  • "3x3="+9
    Notice: We just added the number 9 to a string and received a string back. JavaScript automatically converts 9 into a string before merging it.

6 - Basic Logic

Equal to

If we want to create a practical program we will eventually need to ask the computer to check something. The simplest check we can have the computer perform is whether or not two things are equal. Once we enter a condition, the computer will respond with either true or false. In most programming languages the syntax for `equal to` is ==. For example if I wanted to check that 1 is equal to 2 I would write 1==2 and the computer would respond with false. If I wanted to I could also have the computer check if two mathematical expressions are equal, for example (1+1)==(5-3). All of the examples in this section are just to get comfortable with basic logic, in practical programming checks such as `equal to` are applied mainly to variables. In JavaScript we can use the `equal to` operator to compare numbers, strings, arrays and even more.

Exercise:

Enter the below individually into the JavaScript console or try your own.

  • "MyString"==2
  • "Daniel"=="Cool"
  • "Daniel"=="Daniel"
  • 1==1
  • 1=="1"
    Notice: The number 1 is equal to the string "1", JavaScript converts string numbers into numbers.
  • (55+3*392)==(1233-2)

Not Equal To

What if we want to have the computer check if two things are not equal to eachother? In JavaScript the syntax to do this is !=. While most programming languages use this syntax, there are many which do not, make sure you check before using it. In JavaScript we can use the `not equal to` operator to compare numbers, strings, arrays and even more.

Exercise:

Enter the below individually into the JavaScript console or try your own.

  • "MyString"!=2
  • "Daniel"!="Cool"
  • "Daniel"!="Daniel"
  • 1!=1
  • 1!="1"
  • (55+3*392)!=(1233-2)

Greater Than/Less Than

We can also have the computer compare two numbers. If we'd like to know if one number is bigger than another we would use the `greater than` operator >. For example 4>2 would return true. If we'd like to know if one number is smaller than another we would use the `less than` operator <. For example 2<4 would return true. In any language we can only use the `greater/less than` operators to compare numbers.

Exercise:

Enter the below individually into the JavaScript console or try your own.

  • 1523>145
  • 10*9*11>11*12*8
  • 10*9*11<11*12*8
  • (1+48-212)>(39-32*3)
  • (1+48-212)<(39-32*3)
  • 5<5
    Notice: false is returned because 5 is not less than 5.
  • 5>5
    Notice: false is returned because 5 is not greater than 5.

Greater Than or Equal to / Less Than or Equal to

What if we want to include scenarios when the two numbers are equal to eachother. If we'd like to know if one number is bigger than or equal to another we would use the `greater than or equal to` operator >=. For example 4>=4 would return true. If we'd like to know if one number is smaller than or equal to another we would use the `less than or equal to` operator <. For example 4<=4 would return true. In any language we can only use the `greater/less than or equal to` operators to compare numbers.

Exercise:

Enter the below individually into the JavaScript console or try your own.

  • 1523>=1523
  • 1523>=1522
  • 1523>=1524
  • 5<=5
    Notice: now true is returned because 5 is equal to 5.
  • 5>=5
    Notice: now true is returned because 5 is equal to 5.

And

So far we have only dealt with single conditions. What if we need to know if two separate conditions are both true? In this case we would use the `And` operator. In JavaScript the syntax for the `And` operator is &&. To join two separate conditions we simply write && between them, for example 2>1&&1>0 would return true because both conditions are true. We can combine as many conditions we like with the `And` operator.

Exercise:

Enter the below individually into the JavaScript console or try your own.

  • 1523>=1523&&1523>=1522
  • 1523>=1523&&1523>=1524
    Question: why did this return false?
  • "Daniel"+1=="Daniel1"&&"Daniel"!="Smelly"
  • "name"=="MyName"&&1+1>=2&&4*3*29>=200&&25>=5*8*6

Or

The `And` operator checks if all of the conditions are true. What if we only care if one of them is true? In this case we would use the `Or` operator. In JavaScript the syntax for the `Or` operator is ||. To join two separate conditions we simply write || between them, for example 2>1||1<0 would return true because at least one of the conditions is true. We can combine as many conditions we like with the `Or` operator.

Exercise:

Enter the below individually into the JavaScript console or try your own.

  • 1523>=1523||1523>=1522
  • 1523>=1523||1523>=1524
    Question: why did this return true and not false?
  • 2+2==5||5==10-6
  • "Daniel"+1=="Daniel1"||"Daniel"!="Smelly"
  • "name"=="MyName"||1+1>=2||4*3*29>=200||25>=5*8*6

7 - Introduction to Variables

Variables

Variables are places holders for numbers, strings, booleans, arrays or any other type of data we'd like to incorporate into our program. For example, if I have a very complicated number, 127341278946, which I only every want to write once, I can label this number as the letter a by creating a variable. In JavaScript the code would be var a=127341278946. Once that code is entered the computer will always remember that the letter a represents the number 127341278946. So whenever I write a I am essentially writing 127341278946.

Every programming language has a different syntax for defining variables, some can be quite annoying. In JavaScript it is very easy, you write var then the letter which you'd like to be a variable, var a, then what you'd like that letter to represent, var a=127341278946. Variables don't have to be represented by single letters, they can also be words, for example var bignumber=127341278946.

If our variable represents a number, then we can use all of the mathematical operators we learnt above on it. If it represents a string, we can treat it exactly how we treated strings above. If we'd like to apply some logic to our variable, we can do so in exactly the same way as above. We just need to remember exactly what our variable represents, a number, string, boolean, etc.

If we know later in our code we'll need to use a variable, but right now we don't want to store any data in it, we can simply run var myvariable. This will tell the computer that myvariable is a variable, but at the moment it is undefined. Because we have created the variable, we can use it without receiving any errors.

If we ever try to use a variable in JavaScript which has not been created, we will receive an error saying the variable is undefined.

Exercise:

Individually enter the below examples into the JavaScript console. Every time you define a new variable, enter that variable into the console to see what it represents.

  • var z=5135235
  • var bignum=10*21*2-2
    Notice: JavaScript evaluates the mathematics then sets bignum equal to the result.
  • var astring="MyString"
  • var myname="Daniel"
  • var year=2016
  • var date="2016-01-01"
  • var date="2020-10-10"
    Notice: we have overwritten the date "2016-01-01", now date represents "2020-10-10".
  • Enter var newvar into the console.
    Notice: JavaScript returns undefined.
  • Enter anothervar into the console.
    Notice: JavaScript returns an error.

Mathematics with Variables

If our variables represent numbers we can perform any mathematical operation to them. In the below examples we will be entering more than one line of code. It is important to note here that the computer executes the code you enter from top to bottom. It is also important to note that the symbol ; is used to tell the computer to move to the next section of code. It tells the computer that you are finished with that statement and that it should move on. As you saw above it is not always necessary, but it is good practice to get used to writing it.

Example:

Enter the below sets of code into the JavaScript console.

  • var z=51335;
    var b=4789;
    z+b
  • z+b+(z*b+2*b)/z
  • var year=2016;
    var birthyear=1991;
    var age=year-birthyear;
    age
  • var num=15;
    var diff=10;
    var anoth=0.14124;
    num*diff/anoth
  • var ten=10;
    var six=6;
    var ten=3;
    six+ten
  • Notice: we have overwritten the variable ten with the number 3.

Appending String Variables

Just like above, we can append two variables together if they both represent strings.

Exercise:

Enter the below individually into the JavaScript console.

  • var z="Hello";
    var b="There";
    z+b
  • Notice: there is no space between the words, we need to add it in.
  • var z="Hello ";
    var b="There";
    z+b
  • Notice: there is now a space, we could of also put the space before the `There`.
  • var year=2016;
    var birthyear=1991;
    var age=year-birthyear;
    var iam="I am ";
    var yo=" years old.";
    iam+age+yo
  • var day=15;
    var month=4;
    "The date is "+year+"/"+month+"/"+day
  • var times='*';
    var ten="Ten";
    var six="Six";
    var ten="Three";
    six+times+ten
  • Notice: we have overwritten the variable ten with the string "Three".

Overwriting Variables

In above examples you saw that whenever we redefine a variable it is overwritten to be the new value. This means that the original value of the variable is lost. While this may seem negative, it is often very useful to overwrite variables. This will be especially useful when we learn about loops in coming sections. Here it is important to notice that once the variable has been defined, it is no longer necessary to write var infront of it. The syntax var is purely used to tell the computer that the letter/word is a variable.

Exercise:

Enter the below sets of code individually into the JavaScript console.

  • var z="Hello ";
    var b="There";
    z=z+b;
    z
  • Notice: there is no space between the words, we need to add it in.
  • var num=10;
    var add=4;
    num=num+add;
    num=num+add;
    num=num+add;
    num
  • var students="Student ";
    var s=1;
    var and=" and ";
    students=students+s+and;
    s++;
    students=students+s+and;
    students

Basic Logic with Variables

We can also apply all of the basic logical operators to variables just like we did with numbers and strings.

Exercise:

Enter the below sets of code individually into the JavaScript console.

  • var z=51335;
    var b=4789;
    z==b
  • z!=b
  • z>b
  • z<100000
  • var h="Hello";
    var t="There";
    h==t
  • h!=t

8 - Booleans

Booleans

Booleans are just like numbers and strings except they can only take two possible values, true or false. Booleans are useful to store precalculated logic or to use as dynamic switches. To create a Boolean variable write var a = true;. We can apply logical operators to Booleans such as, Equal To, Not Equal To, And, Or.

Exercise:

Individually enter the below examples into the JavaScript console.

  • var b=true;
    var f=false;
    Notice: there are no quotations around true or false, this is because they are not strings, they are Booleans.
  • b&&f
  • b&&2>1
  • b||f
  • b==f
  • b!=f

9 - Arrays

Arrays

So far we have only created individual variables. Each time we want to access the data stored within that variable we must enter the letter/word into the console. This is very painful if we are dealing with lots of different variables, each with a different name. Instead what we can do is create a list of all the different information we'd like to store. Such lists are called Arrays and can also be represented by variables. Arrays can be lists of numbers, strings, booleans, other arrays and more. You can even have Arrays with numbers and strings and booleans etc. To write an Array in JavaScript the syntax is [50,60,70]. The square brackets tell the computer to expect an array. The commas separate each of the entries inside the array. We can access each of the entries individually by referencing what number it is in the list. The numbering of Array entries starts at 0 and increases by 1 for every successive entry. For example if we wanted to get the number 50 out of the array we would write, [50,60,70][0], because 50 is the first entry and the reference number of the first entry is 0. If we wanted 70 we would write [50,60,70][2]. The second set of square brackets is used to tell the computer which entry in the Array we'd like to get.

Exercise:

Individually enter the below examples into the JavaScript console.

  • ["Daniel",31245235,true][2]
  • ["Daniel",31245235,true][1]
  • ["Daniel",31245235,true][0]
  • var array=["First Entry","Second Entry","Third Entry"];
    array[0]
  • array[1]
  • array[2]
  • var multiarray=[["First Entry 1","First Entry 2"],["Second Entry 1","Second Entry 2"],"Third Entry"];
    multiarray[0]
  • multiarray[0][0]
  • multiarray[0][1]

10 - If Statements

If

We now know how to have the computer determine if particular conditions are true or false, but how can we make it actually do something depending on the result? To have the computer actually do something we need to have it ask itself a question. In programming such a question is called an If statement. The computer will check if a condition is true or false and if it is true, we can program it to do something. Writing If statements can require several lines of code and for this reason text inputs will be introduced for you to write and execute your code. From here on out the exercises will be less copy and paste to more worded so you can write the solutions yourselves.

The standard structure of an If statement is:

if(Enter Condition Here){
    Enter code you want to run if the conditions is true
}


If you'd like to check another condition after you have check the first, you can write an If statement within another if statement. Below is an example of a simple If statement, it checks if 1+1==2 and if it does, it creates a new variable and shows it in the console. From now on if you'd like to print the value of a variable into the console write log(variable in here). We will learn how this works soon.


var t;
if(1+1==2){
    t="It was true!";
    log(t);
}

If you would like to save all of the code you write, Right Click This Link, click Save As, then save the file to your desktop. Once on your desktop right click the file and open with Notepad or Wordpad. Between the <script> and </script> you can write your code. To run the code open the file in Google Chrome, then enter the variables into the console to see their value.

Exercise:

Answer each of the following by entering code in the relevant text field. Click run to run your code.

  • Write some code to check if 2*4*3+58*8==488 and 40+35*3/2==92.5 then if it is true create a variable which stores First Example and print it to the console.
  • Create two new variables and write an if condition which prints Not Equal to the console if they are not equal then forces them to be equal.
  • Create two new variables which store the numbers 20 and 10 respectively. Find a true condition which relates the two new variables by writing an if statement with that condition and printing Correct to the console when the condition is true.
  • Create an array with two entries 54 and 390. Write an if statement to check if the two entries are not equal, if they are not then force them to be equal. Write a second if statement to double check that the two entries are now the same and if they are print "They're the same." into the console.
  • Create an array with 2 entries that are Level1 and Level2. Write an if statement which checks if the first entry is Level1 , then if it's true write another if statement which checks if the second entry is Level2 and if that is true print Both True to the console.

11 - Comments

Commenting your Code

Now that our code is getting more complicated we should start to leave messages for ourselves so we understand what is happening. The perfect place to leave these messages would be within the code itself, but we don't want to enter some text and start receiving errors. What we can do is enter comments. Every coding language allows for text to be written within your code provided that you have `commented it out`. Every language has different syntax for comments, in JavaScript you write // before your text. What this does is tells the computer to completely skip that line in the code.

Below is an example of an if statement with comments in it. If you run this code in the console you will get the same result as you did above, because the computer has ignored all of the extra text I have added due to the //.

// Create a new variable called t
var t;
// Check a mathematical expression
if(1+1==2){
    // The expression was true, so print it to console
    t="It was true!";
    log(t);
}

Exercise:

Comment your above if statements to explain what is happening.

12 - Else Conditions

Else

At the moment we have only told the computer to act on conditions if they are true. If they were false, the computer just did nothing. What if we'd like the computer to check if a condition is true, and if it isn't do something else? In this scenario we would use an Else statement.

An example of an Else statement is shown below.

// Create a new variable called t
var t;
// Create some new number variables
var a=1;
var b=2;
// Check a mathematical expression
if(a+b==3){
    // The expression was true, so print it to console
    t="They added to 3.";
}else{
    t="They didn't add to 3."; 
}
log(t);

Exercise:

Answer each of the following by entering code in the relevant text field.

  • Write some code which will log "Correct User" if a username variable is "Daniel" and "False User" otherwise.
  • Create a variable called numby which is equal to 21. Write some code which will add 43 to numby if numby is less than 100 and multiply number by 2 otherwise. Log numby at the end of the statement. Rerun the if/else condition to see if the statement is working correctly.
  • Write some code which checks if a variable is 32, if it is divide it by 8, if it isn't force it to be 32.

13 - Else If Conditions

Else If

Right now we can check if a condition is true, do something, or if it is false then do something else. In some scenarios we need to be able to do more than this. What if we only wanted to do the `Else` part if a particular condition was true, and if that condition was false we wanted it to do something else? In this scenario we would use an Else If statement.

An example of an Else If statement is shown below.

// Create a new variable called t
var t;
// Create some new number variables
var a=1;
var b=2;
// Check a mathematical expression
if(a+b==2){
    // The expression was true, so print it to console
    t="They added to two";
}else if(a+b==4){
    t="They added to 4."; 
}else{
    t="They didn't add to 2 or 4."; 
}
log(t);

Exercise:

Answer each of the following by entering code in the relevant text field.

  • Write some code which will log "Correct User" if a username variable is "Daniel" otherwise if the username is "Admin" log "It is the Admin" otherwise log "Not an admin or a user".
  • Create a variable called numby which is equal to 2. Write some code which will double numby if it is less than 10, add 50 to numby if it is less than 232 and subtract 100 from numby otherwise. Log numby at the end of the statement. Edit the code so you can run it multiple times and check if your if/else/else if statements were correct.
  • Create a variable called anumber and set it equal to any number you like. Write some code which will logs "The number is positive" if it is positive, "The number is negative" if it is negative or "The number is zero" if it is zero.
  • Create a variable called input and set it equal to anything you like. Write some code which checks if input is nothing, if it is log "Please complete the form", otherwise if it is greater than 0 log "Please do not enter a number", otherwise if it is less than 0 log "Please do not enter a number", otherwise log "Thanks for your input".

14 - Introduction to Functions

Functions

Up until now if we wanted to run a section of code more than once, we had to repeatedly rerun it/refresh the page. What we can have the computer do is remember a set of code which we can refer to and run at any time just by entering in a single command. To do this we will create what are known as functions. Functions are the most important aspect of programming as they significantly reduce the amount of work which is required from the programmer. We can enter anything we have learnt so far within a function, an if condition, a mathematical operation, a string manipulation, anything.

An example of how to create a function in JavaScript is shown below:

var num=1;
function addone(){
	num=num+1;
}
addone(); // Run the function

To execute a function you must write the functions name followed by (). The two brackets tell the computer to execute all of the code stored within the function. If you enter in a functions name without these brackets, Google Chrome will return to you all of the code associated with that function.

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Create a function called double which multiplies an already defined variable by 2 and logs the result.
  • Create a function which adds "and then" to the end of a string every time it is run. Make sure there are spaces between each word and logs the result.
  • Create a function which adds 2 to a variable if it is less than 10 and subtracts 2 otherwise then logs the result.
  • Create a function switchUser which checks if a variable called user is "Daniel" and if it is sets the user variable to "Jessica". If the user is not "Daniel" but is "Jessica" it sets the user variable to "Other". If the user is "Other" it sets the user variable back to "Daniel". At the end of the function it logs the current value of the user variable.

15 - Functions which Return Values

Return

In the above examples we had to use the log function to log our results to the console. What if we wanted out function to give us the result, rather than the console? To do this we use the return command. What return does is provides us with whatever value we have asked it to return then immediately ends the function. For example say we wanted to perform a calculation and store the result somewhere so we can use it later. We could write a function which returns the result and store that result into a new variable.

An example of how to create a function which returns a value in JavaScript is shown below:

var num=1;
function addone(){
	num=num+1;
    return num;
}
addone(); // Run the function
var anothernum=addone(); // Store the result in anothernum, if we run this only once, anothernum would equal to 2.

Any code we enter within the function, after the return will be completely ignored. Notice how in the last line of the example we have set a new variable called anothernum to be equal to the function. What happens is that the computer first calculates addnone() then stores the result in the new variable anothernum.

Exercises:

Answer each of the following by entering code in the relevant text field.

For extra practice repeat each of the above questions on Functions but store the results in variables instead of logging them to the console.

  • Create a function which checks if a number is bigger than or equal to 10 or less than 10. If the number is less than 10 return true, otherwise return false. Use this function in an if condition, if it's true then log "It was less than or equal to 10" otherwise log "It was more than 10".
  • Create three functions. One which returns the string "Hello", another which returns "there" and the last which returns "Daniel". Use these three functions to build the sentence "Hello there Daniel" by merging them together as you would do with a string.
  • Create three functions. One which returns 1, another which returns 2 and the last which returns 3. Use these three functions to calculate 2+1+3*3*3+2*3+1.

16 - Functions with Inputs

Inputs

While we have already significantly improved the efficiency of our programming we can take one further step. All of the above functions did very specific tasks and all of the numbers and strings involved were programmed into them. What if we wanted to make a function which, for example, could add any number we wanted to 1. This means that we need to tell the function what number we'd like to add. We can do this by giving the function an input.

The code for creating a function with a single input in JavaScript is shown below:

var num=1;
function add(x){
	num=num+x;
}
add(1);
add(10);
add(1234);

We enter the number we'd like to add between the two brackets. What this does is replace every x in the definition of the function with the number you enter. For example if you entered the number 10, the function would execute num=num+10;.

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Create a function which multiplies a variable by any number you choose.
  • To log something to the console in JavaScript you must write console.log("what you want to log"). Create a function with a simple name which logs things to the console.
  • Create a function which adds whatever words you want to a sentence and log the sentence each time something new is added.
  • Create a function which multiplies any two numbers you want together and returns the answer.
  • Create a function which adds any two numbers you want together and returns the answer.
  • Use your answers to the previous to create a function which first, multiplies any two numbers you want. Then to the result adds the sum of the two inputted numbers. Then returns the final result.

17 - Useful JavaScript Functions

JavaScript contains a whole library of different functions that we can use. Some of these functions are specific to the type of variable we are working with. For example strings have a whole set of functions just for themselves, as do arrays. If you'd like to see a complete list of all the useful JavaScript functions click here. If you'd like examples on any of the functions either Google them or check out w3schools

Mathematics Functions

There are a whole range of different mathematical functions which are available. We are going to focus on the more practical ones. To access each of the functions we need to call the Math library by writting Math. before each of the functions. For example Math.abs(-1) calls the abs function from the Math library.

FunctionExampleDescription
Math.abs(input)Math.abs(-1)=1Turns the input into a positive number.
Math.ceil(input)Math.ceil(1.001)=2Rounds the up input number to the next higher whole number.
Math.floor(input)Math.floor(1.999)=1Rounds the down input number to the next lower whole number.
Math.round(input)Math.round(2.5)=3;Math.round(2.4)=2Rounds the number to the nearest whole number.
Math.sqrt(input)Math.sqrt(4)=2Takes the square root of the input number.
Math.random()Math.random()=0.584635454Returns a random number between 0 and 1.
Math.pow(input,power)Math.pow(2,3)=8Multiplies the input number by itself 'power' times.

For more mathematics functions click here.

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Create a function which multiplies an input number by a random number. Run it a few times for the input number = 10 and determine what the largest and smallest possible numbers it will are.
  • Create a function which adds an input number by a random number. Run it a few times for the input number = 3 and determine what the largest and smallest possible numbers it will are.
  • Create a function which generates a random number between two inputted numbers.
  • Create a function which takes an input number and returns true if the input is a multiple of 4 and false otherwise. (Hint: Use Math.floor(input/4)==input/4 somewhere in your code)

String Functions

The JavaScript functions for strings are mainly related to manipulating and searching through the characters of a string. We can access these functions on whatever string we like. For example "My String".toUpperCase() applys the toUpperCase function to the string. This works in a similar way to the Math library, except here JavaScript recognises that "My String" is a string and calls the toUpperCase function from its library of string functions. We can even apply these functions to variables provided they are strings, e.g. var t="My String";t.toUpperCase();.
Important: You can only access these functions if you have a string, "My String".toUpperCase(), you cannot just write toUpperCase().

FunctionExampleDescription
charAt(index)"Hey".charAt(0)="H"Returns the character at the index provided.
indexOf(input)"Hello there".indexOf('there')=6Searches for the input string inside the base string and returns the index if it is found or -1 if it is not found.
length"Long String".length=11Returns the length of the string.
toLowerCase()"HEY".toLowerCase()="hey"Converts all characters in the string to lower case.
toUpperCase()"hey".toLowerCase()="HEY"Converts all characters in the string to upper case.
replace(this,that)"Hi Daniel".replace("Hi","Bye")="Bye Daniel"Searches the string for 'this' and replaces it with 'that'.
slice(start,finish)"The Banana".slice(1,-3)="he Ban"Returns the string between the start and finish inputs. Negative numbers mean going backwards from the end of the string.
substr(start,finish)"The Banana".substr(1,6)="he Ban"Almost exactly the same as slice but doesnt take negative inputs. substr is the common syntax for this feature (rather than slice).
split(input)"That,was,cool".split(",")=["That","was","cool"]Splits the string by the input variable into an array of all the strings which were separated by the input variable.

For more string specific functions click here.

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Create a function which checks if an inputted string is a website URL or not. It returns true if the input is a website and false otherwise. (Hint: use .indexOf('http')>=0 somewhere in your code)
  • Adjust the above function so that if the input is a url it returns the url of the website without the "http://" part. (Hint: there are a few ways to do this, try answering this using something like .replace('http://','') )
  • Create a function which replaces all square and curly brackets [, ], {, } with nothing. (Hint: you will need to use 4 separate .replace's)
  • Create a function which splits a sentence up into an array which contains the individual words as each of its elements. (Hint: use .split, what character is between every word in a sentence?)

Array Functions

The build in JavaScript functions for arrays are mainly related to writing/extracting information into/out of arrays as well as some manipulating them. We can access these functions on whatever string we like. For example "My String".toUpperCase() applys the toUpperCase function to the string.

FunctionExampleDescription
concat(value1,value2,...,valueN)["Hi"].concat(["There"],["Nope","Bye"])Enters all of the inputs into one single array. If two arrays are entered, they will be merged into a single array.
indexOf(input)["Today","Its","Cold"].indexOf('Cold')=2Searches for the input string inside the entire array and returns the index of the element which contains the string or -1 if it is not found.
length["Today","Its","Cold"].length=3Returns the number of elements in an array.
push(value)["Today","Its"].push("Cold")=["Today","Its","Cold"]Adds the input value to the end of the array, increasing the arrays size by 1.
pop()["Today","Its","Cold"].pop()=["Today","Its"]Removes the last element in an array, reducing its size by 1.
toString()["Today","Its","Cold"].toString()=Today,Its,ColdReturns the array as a string where all the elements are separated by a comma.

For more array specific functions click here.

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Create a function which searchs array for an inputted value then returns the element which equalled the value if it was found and return "Not found" otherwise.
  • Create a function adds an inputted value into an array.

Other Useful Functions

Below is a list of other useful functions from the JavsScript libraries.

FunctionExampleDescription
isNaN(input)isNaN('hey')=trueReturns true if input is a not a number and false otherwise.
Number(input)Number("1")=1Converts the input into a number and returns the number, if the input is not a number it returns NaN.
setTimeout(function,runin)setTimeout(function(){alert('hello');},1000)Runs the input function after 'runin' milliseconds.
setInterval(function,every)setInterval(function(){alert('hello');},1000)Runs the input function every 'every' milliseconds.

For more JavaScript functions click here.

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Create a function which multplies two input numbers together after checking they they're both numbers. If either of them isn't a number, return false.
  • Create a variable called counter. Create a function that adds 1 to counter then run it every second.
  • Create a function which checks if counter is a multiple of 60. If it is log "One minute has past." to the console. Make this function run twice every second.

18 - Variables in Functions

Private Variables

Up until now we have been creating variables by writting var variable outside of functions. There may be some scenarios where within out function it would be easier for us to create new variables to simplify out code. These variables are called Private Variables. They are called Private Variables because they only exist within the function, no other function or piece of code can access them. Once a function has completed running they are forgotten by the computer. You have to be careful when defining new variables within functions. If you have defined a variable daniel outside of the function, the decide to redefine it inside the function, whenever you referrence daniel inside the function you will be referring to the new, private variable NOT the daniel variable you defined outside the function. If you try to access a variable which was defined within a fuction, outside of the function, you will receive an error.

  • Variables defined outside of functions are called Global Variables because they can be accessed by any part of your code.
  • Variables defined inside of functions are called Private Variables because they can be accessed within the function they were defined.

var num=1;
function add(x){
	num=num+x;
    var variable=x+1;
}
log(variable);

Notice when running that code you received an error, this is because variable was a private variable.

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Create a function which takes an array as the input then switches the first and the last elements then logs the array in String form.

19 - Recursive Functions

Recursive Functions

There is nothing stopping us from calling a function from within itself. These types of functions are called recursive functions. When designing a recursive function it is very important that you including a point in which the function stops calling itself. If you don't include this, the function will repeat over and over and over until either you close Google Chrome, or your computer crashes.

var num=1;
function add(x){
	num=num+x;
    if(num<10){
    	add(x);
    }else{
    	log(num);
    }
}
add(1);

In this example the function keeps adding 1 to the num variable until it reaches 10. Once it reaches 10 the function stops calling itself and finishes by logging num.

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Create a recursive function which adds 10 to a variable until the variable reaches 1000.
  • Create a recursive function which adds " and then " to the end of a variable until the length of the string is bigger than 255.
  • Create a recursive function which takes two input numbers, a number to be powered and the power. Make the function calculate the inputed power of the inputed number.
  • Create a recursive function which separately logs every element inside of an array.

20 - For Loops

For Loops

For loops are very similar to recursive functions. What a For loop does is run a section of code over and over and over according to the rules you have provided it with. There are three rules we must provide a for loop.

  • A starting point var i = 0. This means we start with i = 0.
  • An ending point i < 10. This means we keep loading the code until i no longer satisfies i<10.
  • A condition on how the variable i changes after each run of the code i++. This means after each run of the code, we add 1 to i.

var num=1;
for(var i=0;i<10;i++){
	num=num+1;
}
add(1);

Exercises:

Answer each of the following by entering code in the relevant text field.

  • Make a function which takes an input number to the power of a second inputted number using a For loop.
  • Make a function which adds all the elements in an array together using a For loop.
  • Make a function which creates an array of 20 numbers where the value of the first element is 1, the second 2, and so on until 20 using a For loop.
  • Make a function which creates an array of 20 numbers where every first number is 1 and every second number is 2 using a For loop.
  • Make an function which adds together all of the elements in an array, e.g. addArray([1,2,3,4,5],[2,3,6,7,10]) would return [3,5,9,11,15] using a For loop.

21 - Web Development

HTML

HTML is the language used to structure web pages. It includes a whole range of different types of elements, for example input boxes, buttons, tables, check boxes and so on. Basically everything you see on a web page is constructed using HTML.

To save the HTML attributes template right click here and click save as.

HTML Attributes

Each HTML element can have a unique set of "attributes". Attributes are kind of like properties for those elements. In particular the id attribute is a unique identifier which we can use to select that particular element using JavaScript. Other useful elements are class, which helps for styling, href, which is for referring users to different web pages, and onclick, which is used to run JavaScript functions.

To save the HTML attributes template right click here and click save as.

Useful Includes

You can include prewritten JavaScript code, packages, styling, fonts and a whole range of other things into your website. Below is a list of some useful packages. To include a package into your website all you need to do is paste the provided code into between the two head tags of your website.

  • jQuery - A packages of thousands of useful functions for JavaScript.
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  • FontAwesome - A package of hundreds of easy to use icons, view all the icons here.
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
  • Simple Popups - A small package to include popups in your website, info on how to use it here here.
    <script src="https://cdn.rawgit.com/vast-engineering/jquery-popup-overlay/1.7.13/jquery.popupoverlay.js"></script>
  • Slideshows - A small package to include Slideshows in your website, info on how to use it here here. To use this package you'll need to download the .js file and include it in your project (this is a little harder than the above packages).

Interactive Web Development

Now that we know the basics of web development we can start controling how the user interacts with the web page using JavaScript.

Example:

Click on the below links to view the example, right click it and click save as to save the code.

Calculator

Login Form

Math Game

Clicker Game

Popup

Slideshow

Projects

Below is a list of projects which can be made using all the tools we have learnt so far.

To-do List

  • A list with a text input in it.
  • A button.
  • When you press the button, another entry is added to the list.

Discount Calculator

  • A number input for price
  • A dropdown menu (select) for discount percentage.
  • A calculate button.
  • A div to store the discounted price.
  • When you press calculate the discounted price is calculated, and stored in the div.

Basic Photo Gallery

  • Several images (can use url's from google).
  • A back button.
  • A next button.
  • When you click back or next, the previous or next image is shown.

Dice Roll

  • A div to store the result in.
  • A button.
  • When you click the button, the result of the dice roll is stored in the div.

Lucky 8 Ball

  • A div to store the result in.
  • A button.
  • When you click the button, a lucky 8 ball message is stored in the div.

Comment Feed / Chatbox

  • A div to store all the comments/messages in.
  • A text area to enter comments/messages into.
  • A button to send messages.
  • When the button is pressed, the message is placed inside the div.

Trivia Game

  • A div for the question.
  • A text input for the answer.
  • A button to answer the question.
  • When you click the answer button, you are notified if you are correct or not.
  • If you are correct, another question is posted.

Typing Trainer Game

  • A div to store the text to type.
  • A text area for the user to type into.
  • As the user types, check whether what they have typed is the correct text to type.
  • If what they have typed is correct, empty the text area and change the text to type.

Picture Clicking Game

  • An image.
  • A button.
  • When you click and hold the button, the image size increases.
  • When you release the button, check if the image is the correct size.
  • If the image is the correct size, you are alerted that you win.
  • If the image is not the correct size, the image size is reset and the player tries again.