WK4: Introduction to Javascript

Javascript

Javascript (or JS) is a ‘client-side’, or ‘front-end’ scripting language. This means that the browser runs the code, instead of the server (back-end). The ability to run code inside the browser allows us to make a website far more dynamic and interactive than if we didn’t have access to Javascript.

We can use Javascript for changing the content of the page (without needing to refresh the browser), respond to user inputs, make calculations, and more.

Javascript is one of the most-used programming languages in the world, and therefore help and resources are abundant and easy to find.

Javascript Resources

This week’s tutorial will cover the following:

Note that we will not be manipulating our website very much this week, this will be covered next week using jQuery, however, it is possible to manipulate our DOM with normal Javascript.

HOW TO INCLUDE JAVASCRIPT IN YOUR HTML FILE

We’re going to start with a simple file to work from. The HTML5 boilerplate we used last week is a bit overkill for our purposes. We’ll create two files in a folder, one called index.html, and another called main.js. Our Javascript file is then linked right at the end of the body. This is to stop something called ‘render-blocking’ – where the HTML stops loading so that the Javascript can run.

<!DOCTYPE html>
<html>
    <head>
        <title>Tutorial 3 - Javascript</title>
    </head>
    <body>


        <script src="main.js"></script>
    </body>
</html>

If we then put the following code into our main.js file and refresh our HTML page, we can see some content appear, created by the Javascript file. The document.write(); syntax is used for demonstration only, it is very unlikely that you will use this code in your website.

document.write("Hello World!");

Another thing we can add to our Javascript file is comments. Just like how we could add comments in HTML and CSS, we can also comment in Javascript. This is usually used for explaining to your colleagues what you were thinking when you wrote a piece of code. Sometimes code can be self-explanatory, while other times you might need to explain what you’re doing and why.

// This is a single-line comment

/* This is a
Multi-line
Comment */

/*
I can add code inside this and it won't run
*/

The Console

Earlier, we used the document.write(); function to add some code to the document. If we don’t want to change the HTML document when we write our Javascript, we can use the less-invasive console.log(); function. If you add the following into your Javascript file, and open your Javascript console, you can see the results. The Javascript console is opened differently in different browsers (Safari, Opera, Internet Explorer, and Edge excluded):

console.log('Hi DXB301!');

Variables

In our code, we can also store data. This is called a variable, similar to what we use in algebra when we write things such as x and y.

Let’s create some simple variables:

// We can create variables like this:
var myFirstVariable;

// But that variable is 'null', we should assign it a value:
myFirstVariable = 1;

// We can also do both of the previous steps at the same time if we want to:
var mySecondVariable = 2;

// And we can log these variables to the console:
console.log( myFirstVariable );
console.log( mySecondVariable );

// We can even change (reassign) a variable after it's created:
myFirstVariable = 9000;
console.log( myFirstVariable );

We can’t use spaces inside our variable names inside Javascript – they won’t work! While we usually use hyphens in CSS and HTML for things such as classes (e.g button-blue), we use something called ‘Camel Case’ in Javascript (e.g buttonBlue).

We can create different types of variables. For example, the variables shown in the code above are numbers, but we can also create a string variable, which is a sequence of characters, or to put it simpler – text. We can also create a boolean – which can be either true or false. We’ll go into booleans a bit more later.

Let’s create some variables in Javascript, and log what type of variable they are into the console. typeof myVariable will tell us what type our variable is.

// A number is simply a number:
var x = 1;
console.log( typeof x );

// A string is text, it needs to be surrounded with quotation marks ( ' or " ):
var y = "1";
console.log( typeof y );
var z = 'Hello!';
console.log( typeof z );

// A boolean can be either true or false
var a = true;
console.log( typeof a );

We can do some pretty cool things with variables! We can perform maths on them, combine text, and more:

var x = 10;
var y = 5;

var addition = x + y;
var subtraction = x - y;
var multiplication = x * y;
var division = x / y;
var remainder = x % y;

console.log( addition );
console.log( subtraction );
console.log( multiplication );
console.log( division );
console.log( remainder );

// We can also add strings together, create a variable with your name:
var myName = "My Name Here";
// ... and your age:
// (Replace "Your Age Here" with your age!)
var myAge = Your Age Here;
console.log( "Hello, " + myName + ", it's nice to meet you!" );
console.log( "You're " + myAge + " years old!" );

Most of the previous code should be pretty self-explanatory. The % is probably the most confusing. This is called ‘modulus’, it means the remainder when one number is divided by another. For example:

This might not seem useful, but we can use it for a lot of purposes, the most common is determining if a number is odd or even:

Functions

Sometimes, we might want to run the same code many times. Instead of writing the same code over and over again, we can create something called a Function. This will allow us to run code many times. Let’s create a function that says hello inside the console.

function sayHello() {
  console.log("Hello!");
}

The function we just made will not do anything until it is called.

We can call a function by doing the following:

sayHello();

We can make our function even more complex by giving it parameters. This means that our function will run differently depending what parameters we pass it.

Let’s edit our previous function so that it says a more personal hello:

function sayHello( name ) {
  console.log("Hello, " + name + "!" );
}

var myName = "Your name here";
sayHello( myName );

We can also use a function to return a value.

// Let's create a function that adds two numbers together
function addNumbers( x, y ) {
  return x + y;
}

// We can call it with just numbers ...
var total = addNumbers( 1, 2 );
console.log( total );

// ... Or with variables.
var a = 3;
var b = 5;
var c = addNumbers( a, b );
console.log( c );

Conditional (if) Statements

The code we’ve created so far works, but it doesn’t change if we give it different values. Sometimes we might want our code to give a different result if we supply it with different data. The most common way to do this is with an if statement.

We showed a boolean (true / false) earlier. If statements are quite simple, an if statement simply asks a question, and if the question results in true, it runs the code block, if false, it ignores the code. We can also add an else block that will run if the first statement is false.

Let’s make a very simple if / else statement:

var myVariable = true;

if (  myVariable ) {
  console.log("myVariable was true!");
} else {
  console.log("myVariable was false!");
}

But what if, for example, we wanted to ask a more complex question?

We can compare numbers, strings, and booleans using if statements. We can compare with the following:

Let's create a function that returns true if we give it an even number.

// Remember how we used modulus (%) earlier?
function isEvenNumber( number ) {
  if ( number % 2 === 0 ) {
    // This is an even number
    return true;
  } else {
    // This is an odd number
    return false;
  }
}

// Lets run the function a few times:
console.log( "5 is even? " + isEvenNumber( 5 ) );
console.log( "8 is even? " + isEvenNumber( 8 ) );
console.log( "234 is even? " + isEvenNumber( 234 ) );
console.log( "21497 is even? " + isEvenNumber( 21497 ) );

We can also ask more than 1 question when we use an if statement.

For example:

function luckyNumbers( number ) {
  if ( number === 13 || number === 4 ) {
    return "That's an unlucky number!";
  } else if ( number === 7 || number === 42 ) {
    return "That's a lucky number!";
  } else {
    return "That number is pretty boring.";
  }
}

// Lets run the function a few times:
console.log( "5? " + luckyNumbers( 5 ) );
console.log( "7? " + luckyNumbers( 7 ) );
console.log( "13? " + luckyNumbers( 13 ) );
console.log( "27? " + luckyNumbers( 27 ) );
console.log( "42? " + luckyNumbers( 42 ) );

Loops and Arrays

Sometimes, we might want to group values into a list. We can easily do this in Javascript using something called an Array. We can create an array by using square brackets [ ], and entering each item one-by-one with a comma to separate them.

We can also add items to arrays using arrayName.push(newItem); .

And we can see the number of items in an array using arrayName.length;

var berries = ["Strawberry", "Raspberry", "Blueberry", "Blackberry"];
console.log( berries );

// We can also create an array over multiple lines if we want to:
var vegetables = [
  "Onion",
  "Carrot",
  "Bean"
];
console.log( vegetables );

// We can also add items to arrays after we create them:
vegetables.push( "Lettuce" );
console.log( vegetables );

// We can also see how many items an array contains:
console.log( vegetables.length );

Finally, we can print a specific item in the list by using that item’s index. This is the number of the item in the list. The syntax used for this is myArray[index];

An important thing to know about Javascript and many other programming languages is that their numbering system starts at 0. So the first item in our array has an index of 0, our second item is 1, and so on.

Let’s log a few values from an array:

var berries = ["Strawberry", "Raspberry", "Blueberry", "Blackberry"];

// This will log the SECOND item in our array (Raspberry)
console.log( berries[1] );

// This will log the LAST item in our array (Blackberry)
var lastNumber = berries.length - 1;
console.log( berries[lastNumber] );

Sometimes we might need to loop through our code and repeat the same thing. We can do that using a for loop.

Here is an example for loop:

var cities = [
  "Sydney", 
  "Melbourne", 
  "Brisbane", 
  "Perth", 
  "Adelaide", 
  "Hobart", 
  "Canberra", 
  "Darwin"
];

for (i = 0; i < cities.length; i++) { 
    console.log( cities[i] );
}

The code inside the for loop might look a bit strange at first, but it’s really quite simple.

i = 0; – This is our starting value. The code here runs before our loop starts. This variable can be named anything, but it is very commonly named i – for index. This is significant because our loop decides if it should continue looping based off of the value of this number.

i < cities.length; - This is the condition that must be true for our loop to repeat. If this is false, our loop will stop. In this example, the loop stops when we have reached the last item in our array.

i++ - This code runs at the end of each iteration of the loop. i++ is shorthand for i = i + 1

Exercises

Exercise 1

Write a function that returns the square of a number, then test it by using console.log(); for the numbers 25, 7, 19, and 254.

The console should log 25, 49, 361, and 64516

Exercise 2

Create a function that will convert Celsius to Fahrenheit, then create a function that does the opposite.

Log the results F to C for two numbers – 130 and 10. The results should be 54.444... and -12.222...

Log the results C to F for two numbers – 40 and 10. The results should be 104 and 50

Exercise 3

Write a for loop that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number, and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.