Intro To Code

This is a step by step introduction to basic programming concepts, using the Javascript language.

This course should only take a several hours. If you concentrate you can do it in an afternoon or over two evenings. Some of the 'check you understand' sections are intended to be challenging to make sure you think about how the code is working. It's important to try them all but if any of them are too hard, don't worry. So long as you feel you understand the concept, move on to the next section. Once you have completed the course and digested what you have learned, they should become easier.

Most software follows the Input Process Output (IPO) model.

A simple program is like a cooking recipe. It has statements that declare how much of which ingredients to use (inputs and variables), and a set of instructions or procedures to carry out (process or 'control flow' such as loops, conditional statements and functions) to arrive at a finished product (output).

Intro To Code Part 1

Intro To Code Part 2

Plain Text Editor

To get started all we need is a plain text editor, which you may already have. A plain text editor allows you to write text without any extra formatting or anything else that you would get in a word processesor such as MS Word.

On Windows you can use 'Notepad.exe' (Go Start->Search->Notepad). The default text editor on Mac 'TextEdit' can be confusing, so it's probably easiest to download something like Komodo (Choose the 'Komodo edit' tab, not 'IDE'), Sublime, TextMate, or Notetab. These are also good to use on Windows. I use Notetab and Komodo. Make sure you get the free version.

HTML

Javascript is a language for manipulating web pages, so we first need to write a basic webpage using the Hypertext Markup Language, HTML. Since this is about programming, not HTML, we'll just use this simple example HTML page. Basic HTML is easy to understand. Everything in a page is wrapped in an HTML 'tag' or 'element' that says what that thing is, so that your web browser knows how to display it. Every page has a 'head' section with information about the page and a 'body' section which contains the part you can see in your browser window. If your web page has a heading, you wrap it in <h1>heading</h1> tags. Each paragraph is wrapped in a <p>paragraph</p> tag. To learn more about HTML try the W3C tutorial.

Type this (or copy and paste) into your text editor and save it on your computer as index.html:


<html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p>To practice code we will write a simple app to help learn Italian.</p>
    </body>
</html>

Go to where you saved the file and double click it. Because it's a web page, it should open in a web browser. If it doesn't check the filename. It should be index.html, not index.txt nor index.html.txt

NB: If something doesn't work and you can't figure it out, it's likely somebody else has had the same problem and someone has given them a solution in a help forum. A web search is likely to find the answer, though you may have to work through a few possibilities. Don't worry if you go down the wrong path trying to solve a problem - you're sure to learn something that will help solve another bug later.

TIP: To see the HTML of any web page, right click it and choose 'View Source' or 'Inspect Element'.

Check you understand:

Add a level 2 heading with the <h2> tag that says, "and Javascript" and another paragraph that says whatever you like.

Javascript

An HTML page is static. It doesn't change. Javascript is a language for making webpages more dynamic and interactive.

To check Javascript is working, add some Javascript to the header section of your code. The Javascript must be wrapped in the <script> tag</script> so that the computer knows it should interpret this as Javascript commands, and not show it on the page as HTML:

<html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p>To practice code we will write a simple app to help learn Italian.</p>
                <script>
            alert("Hello world!");
        </script>
    </body>
</html>

Refresh the page in your browser, or open it again. It should pop up with an alert saying 'Hello world!'. You have just written some code that works. You don't need a computer science degree to write code :-)

Check you understand:

Make the Javascript alert say, "Hello, Dave. You're looking well today."

Scalar Variables

The information we want to use in a computer program must be stored in a 'variable'. A variable is like a box where you can put data that may vary. You can then re-use it anywhere in your program.

For example if you sign up to a website and enter a username, the program can then use the 'username' variable to display your name in a welcome message, in emails or in reports to the manager. This means you only need one line of code to do the same thing for everyone.

Variables can be of different types: numbers, decimals, strings, boolean, bits etc. Some languages are very strict about what type of variable you are using but Javascript is very forgiving. To declare a variable you just need to use the 'var' keyword.

This simplest variable is a scalar variable - a single item of information. In Javascript we create a variable like this:

var name;

Or, declare a variable and assign a value to it like this:

var name = "Shelley";

Then we can use it in our code by using the variable name, like this:

alert("Hello, " + name + ". You're looking well today.");

So edit your code, putting your own name in the variable and reload:

<html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p>To practice code we will write a simple app to help learn Italian.</p>
        <script>
            var name = "Shelley";
            alert("Hello, " + name + ". You're looking well today.");
        </script>
    </body>
</html>

In this example we have only used the variable once, but you can see that if you use the variable 'name' throughout a large and complicated program you would only need to set it to be a different name in one place and it would take effect wherever we use that variable.

Pop up boxes are annoying, so let's write the welcome message directly onto the page:

<html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p id="greeting">Your name will appear here. 
        </p>
        <p>To practice code we will write a simple app to help learn Italian.</p>
        <script>
                var name = "Shelley";
                document.getElementById("greeting").innerHTML = "Hello " + name;
        </script>
    </body>
</html>

There are a few changes here. We have added an 'id="greeting"' attribute to a <p> tag. This is a label so that our Javascript can find the particular paragraph where we want to show the welcome message.

Remember that Javascript is a language for interacting with and changing HTML web pages. In the Javascript we have a command that finds that particular paragraph and changes its text to be the greeting: document.getElementById("greeting").innerHTML = "Hello " + name;

In Javascript all the parts of the HTML 'document' can be accessed in this way. All the HTML elements are accessed as 'objects'. Understanding objects is an important part of good programming but a little more complex, so we will leave it for the 'intermediate' course. For now it should be enough to understand that an 'object' is a thing in a web page or in the code that can be used or changed. This command does a few things: It gets the whole HTML document 'object', finds the tag that has the id 'Greeting' and set's it to say "Hello " with whatever name you have stored in the name variable.

Check you understand:

Add another paragraph with a different ID, and set its text to say "Goodbye" + name.

Conditionals

One of the most important features of programming is the simple 'if' and 'if else' clause. With 'If-else' we can check if something is the case and run some code, or run some other code if it isn't.

In this example we get the current date and time using Javascript's built-in 'Date' object and compare it's 'hours' to 18 to see if it's day time or evening and say 'Good morning' or 'Good evening':

<html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p id="greeting">Your name will appear here. 
        </p>
        <p>To practice code we will write a simple app to help learn Italian.</p>
        <script>
                var name = "Shelley";
                var italianGreeting = "";
                if (new Date().getHours() < 18) {
                    italianGreeting = "Buongiorno";
                } else {
                    italianGreeting = "Buona sera";
                }
                document.getElementById("greeting").innerHTML = italianGreeting + " " + name;
        </script>
    </body>
</html>

You can check anything you want in a conditional clause, so long as the answer is True or False. It could be if (age > 18) or if(username === "Shelley") and so on. There are 'operators' (such as equals, greater than, less than, not equal to, etc) for comparing things in if statements.

One important thing to remember is not to confuse '=' with '==='.

username = "Shelley"

will set the variable 'username' to be 'Shelley'. To check whether the username is Shelley, to compare it, use

username === "Shelley"

Check you understand:

Make it say 'Buona Notte' if your name is "Shelley". Change the name to and from "Shelley" to check it works.

Arrays

We are supposed to be learning Italian. One thing that could help is a list of Italian words we need to memorise. An 'array' is a variable for containing a list of scalars. Let's make an array of Italian words and show them on screen:

<html>
    <head>
        <title>Learn Code</title>
        <script>

        </script>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p id="greeting">Your name will appear here. 
        </p>
        <p>To practice code we will write a simple app to help learn Italian.</p>
        <p>Remember these words:</p>
        <p id="italian"></p>
        </p>
        
        <script>
                var name = "Shelley";
                var ItalianWords = ["ciao", "gatto", "mangiare", "pasta"];
                
                document.getElementById("greeting").innerHTML = ItalianWords[0] + " " + name;
                document.getElementById("italian").innerHTML = ItalianWords;
        </script>
    </body>
</html>

An array is a list and every item in it has a number. With arrays we start counting at 0 so the 1st item in an array is item 0. If you want to use the first item in an array you can access it like this: ItalianWords[0]. The value of the first item in the array happens to be 'ciao' (which means 'hello') so we have used that for our greeting. We have also set the next paragraph to show all the words in the ItalianWords array.

Check you understand:

Add the word "arrivederci" at the end of the array. Make the greeting say 'arrivederci' using the array.

Loops

The way that javascript is writing out the list doesn't look very good. We should make it into an HTML list so that it looks better. An HTML list starts with the html <ul> tag (for 'unordered list') and ends with the closing tag </ul>. Each item in the list is inside the <li>list </li> tag. Ultimately the HTML list we construct and output will be like this:

<ul>

<li>ciao</li>

<li>gatto</li>

<li>mangiare</li>

<li>pasta</li>

</ul>

To get full control of our array we need to loop through it and add the html <li> tags to each item one by one, and then add it to the page.


<html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p>Welcome 
        </p>
        <p id="greeting">Your name will appear here. 
        </p>
        <p>To practice code we will write a simple app to help learn Italian.</p>
        <p>Remember these words: 
        <p id="italian"></p>
        </p>
    
        <ul id="italianwordlist">

        </ul>
        </p>
        <script>
            var name = "Shelley";
            var ItalianWords = ["ciao", "gatto", "mangiare", "pasta"];
            
            document.getElementById("greeting").innerHTML = ItalianWords[0] + " " + name;
            
            for	(i = 0; i < ItalianWords.length; i++) {
                ItalianWords[i] = "<li>" + ItalianWords[i] + "</li>"
            }
            
            document.getElementById("italianwordlist").innerHTML = ItalianWords.join(" ");
            
        </script>
    </body>
</html>

Note that it doesn't matter how long our list is, it could be millions of words long, and all we need is a few lines of code to do the same thing to every item. That's one thing that makes computers so useful - so long as the data is in a regular and consistent format, you can just loop through it to do work in a few moments that would otherwise have taken hours or billions of years. You can also just use the same program on any new data you get, so long as it's in the same format.

You can put any code you like inside the loop. If we set up the data right we could, for example, use conditional statements check if a word is a verb and highlight it in green.

Here's how the 'for' loop works. First, it sets a variable 'i' to 0. Then we check if 'i' is less than the length of the array. Then we add 1 to 'i'. Then we execute all the code inside the loop. Then we go back to the beginning. This time, i will be equal to 1, and the next time it will be 2, because we add 1 to i, with every iteration. When i is equal to or greater than the length of the array the loop stops. Normally you will never need to alter anything in the loop statement

for (i = 0; i < ItalianWords.length; i++) {

except for the name of the array.

Note also that inside the array we access the particular item in the array with the 'i' variable. The first time through i is 0, so we will be getting the first item in the array ItalianWords[0]. The next time around i will be 1, so we will be accessing ItalianWords[1], and so on.

In this example we are setting each element in the array to be surrounded by the HTML <li> tag. Then at the end, once the loop has finished, we set the contents of the <ul> tag with the id "italianwordlist" to be the newly modified array.

Note also that we use a .join(" ") method on the array to say that we want the array to be written out joined together with spaces instead of the default commas. Javascript is an 'object oriented' language. Some objects have built in 'methods' that make it easier to do things with those objects. The 'array' object has a 'join' method that lets you say how you want the items in the array to be joined together.

Check you understand:

Make a new array called 'ItalianFood' containing "spaghetti, bruschetta, prosciutto, gelati" and another loop to show it as well.

Associative Arrays (Hashes or Dictionaries)

But what if we forget what these Italian words mean? We need their English translation. Another common structure is called an 'Associative Array' in Javascript. In other languages it might be called a 'Hash' or 'Dictionary'. This kind of variable allows us to make a list that associates one thing with another, just like a dictionary is a list of words associated with their definitions. It is a list of 'keys' and 'values'. In our example we want to match the word in Italian (the key) to its English translation (the value).


<html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p>Welcome 
        </p>
        <p id="greeting">Your name will appear here. 
        </p>
        <p>To practice code we will write a simple app to help learn Italian.</p>
        <p>Remember these words: 
    
        <ul id="italianwordlist">

        </ul>
    
        <script>
                var name = "Shelley";
                var ItalianWords = [];
                ItalianWords["ciao"] = "hello";
                ItalianWords["gatto"] = "cat";
                ItalianWords["mangiare"] = "eat";
                ItalianWords["pasta"] = "pasta";
                
                document.getElementById("greeting").innerHTML = ItalianWords["ciao"] + " " + name;
                
                var storeHTML = "";
                
                for (var key in ItalianWords) {
                    storeHTML = storeHTML + "<li>" + key + " means " + ItalianWords[key] + "</li>";
                }
                document.getElementById("italianwordlist").innerHTML = storeHTML;
        </script>
    
    </body>
</html>


Looping through an associative array is similar to looping through an array except you access the value by its key, instead of by a number. In this loop, each Italian word is temporarily stored in the variable 'key'. The loop goes through every key in the array, which can be used to access every value like this: ItalianWords[key].

You can also access a specific value by using a specific key. In this example, in the greeting we have accessed the English word 'hello' by using the key like this: ItalianWords["ciao"].

Note also that we are creating our HTML list slightly differently this time. Instead of changing the values in the array to have the <li> tags around them we have created a new variable 'storeHTML' and we are building up the HTML list in this variable by adding to it with each iteration. That way we can build up some HTML without changing the contents of the associative array itself, which we might want to use in a different way later. We then simply output the value of 'storeHTML'.

Check you understand:

Add the word "arrivederci" and its translation 'goodbye' to the associative array. Make the greeting say 'arrivederci' using the associative array.

Make another loop that shows only the Italian words, and then another that shows only the English words.

In the next section we'll make the webpage interactive with functions and events.