Category Archives: JavaScript

JavaScript Quiz

Here is some code for a simple Quiz program written in JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>
 
<style>
div#test{ border:#000 1px solid; padding:10px 40px 40px 40px; }
</style>
 
<script type="text/javascript">
// pos is position of where the user in the test or which question they're up to
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
// this is a multidimensional array with 4 inner array elements with 5 elements inside them
// if you don't want answers viewable in the code, then you should use PHP and mySQL database
var questions = [
 ["What is 5 + 4?", "10", "9", "7", "B"],
 ["What is 15 - 3?", "11", "13", "12", "C"],
 ["What is 6 x 4?", "24", "26", "21", "A"],
 ["What is 16 / 4?", "6", "3", "4", "C"]
 ];
// this get function is short for the getElementById function 
function get(x){
 return document.getElementById(x);
}
function renderQuestion(){
 test = get("test");
 if(pos >= questions.length){
 test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
 get("test_status").innerHTML = "Test completed";
 // resets the variable to allow users to restart the test
 pos = 0;
 correct = 0;
 // stops rest of renderQuestion function running when test is completed
 return false;
 }
 get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
 question = questions[pos][0];
 chA = questions[pos][1];
 chB = questions[pos][2];
 chC = questions[pos][3];
 test.innerHTML = "<h3>"+question+"</h3>";
 // the += appends to the data we started on the line above
 test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
 test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
 test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
 test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
function checkAnswer(){
 // use getElementsByName because we have an array which it will loop through
 choices = document.getElementsByName("choices");
 for(var i=0; i<choices.length; i++){
 if(choices[i].checked){
 choice = choices[i].value;
 }
 }
 // checks if answer matches the correct choice
 if(choice == questions[pos][4]){
 //each time there is a correct answer this value increases
 correct++;
 }
 // changes position of which character user is on
 pos++;
 // then the renderQuestion function runs again to go to next question
 renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
</script>
</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>
 
</html>

Switch statements

A switch statement is like an IF statement but is neater when working with many conditions. Use the break statement at the end of each case so that the code runs efficiently. If you don’t use break, the program which keep checking through all conditions even if a match has already been found. If none of the conditions are met, then the ‘default’ case will run.

Take a look at the source code below and watch the video here to see switch statements in action.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Switch Statements</title>
 <script type="text/javascript">
 
 // A switch statement is like an IF statement but is neater when working with many conditions.
 // Use the break statement at the end of each case so that the code runs efficiently.
 // If you don't use break, the program which keep checking through all conditions even if a match has
 // already been found. If none of the conditions are met, then the 'default' case will run.
 
 var city="Sydney";
 
 switch(city){
 case "Melbourne":
 document.write("You are from Melbourne");
 break;
 case "Sydney":
 document.write("You are from Sydney");
 break;
 case "Perth":
 document.write("You are from Perth");
 break;
 case "Brisbane":
 document.write("You are from Brisbane");
 break;
 default:
 document.write("You don't live in a city I recognise.");
 }
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Using And/Or Operators in If Statements

Using logical operators such as and/or allow a programmer to write complex if statements. For example, you can check if a number is greater than 10 AND is also less than 20 (both conditions have to evaluate to true for the code to run inside the if statement). Or, you can check if a number is less than 5 OR greater than 10 (only one condition has to evaluate to true for the code to run inside the if statement)

Logical operators:

  • The symbols && are used for the and operator in JavaScript
  • The || symbols are used for the or operator in JavaScript
  • A single exclamation mark ! can also be used as a not operator.

Check out the sample code below to see how these logical operators can be used to form complex if statements in JavaScript, and make sure you also watch the accompanying video here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 // This is a better way than using nested if statements
 // You can use and/or operators in JS (known as logical operators)
 // The AND operator is &&
 // The OR operator is ||
 
 var firstName = "John";
 var lastName = "Smith";
 
 if(firstName=="John" && lastName=="Smith"){
 document.write("Hello, John Smith!");
 // The message above will only be displayed if firstName is John AND lastName is Smith.
 // Try using || instead of && and change the value of one of the variables. What happens?
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Nested If Statements

The sample code below shows how to use if statements inside other if statements (nested if statements). The video here explains all about nested if statements!

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 var age = 21;
 var maxAge = 30;
 var minAge = 18;
 
 // Below is an example of using if statements inside other if statements
 // This is called nested if statements.
 
 if(age>=minAge){
 if(age<=maxAge){
 document.write("You are within the accepted age range.");
 }
 else{
 document.write("You are above the accepted maximum age.");
 }
 }
 else{
 document.write("You are under the accepted minimum age.");
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

If else statements

Often when using if statements, you will want to test more than just one condition. The sample code below explains how to do this. You can also watch the video here which runs through using if, else if, and else statements.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - If Else Statements</title>
 <script type="text/javascript">
 
 // You can have a single if statement (tests one condition)...
 // However, you can also have an IF statement that tests multiple conditions
 // Eg. You can have an if and an else statement (tests two conditions)
 // You can have an if statement, else if statements, and an else statement (tests several conditions)
 
 // if - is the first condition to test
 // else if - is used to test other conditions
 // else - will run a piece of code only if none of the other condition tests have evaluated to true
 
 var age = 16
 
 if(age>=18){
 document.write("You are old enough to vote.");
 }
 else if(age==17){
 document.write("You can vote after your next birthday.");
 }
 else{
 document.write("You cannot vote yet.");
 }
 
 // Make sure you don't confuse the = sign (used for assigning values to variables) for == (used for comparisons)
 
 </script>
 
</head>
<body>
 
</body>
</html>

If statements

An ‘if statement’ is used to test a condition. If the test condition evaluates to true (Eg. x is less than y), then the code inside the if statement will run. If the test condition evaluates to false, then the code inside the if statement won’t run and the program will continue on. Take a look at the video here which explains if statements, and then try using the sample code below.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - If Statements</title>
 <script type="text/javascript">
 
 /* For an 'if' statement, the syntax should look like:
 
 if(condition to be tested){
 //run code here
 }
 
 */
 
 var age = 20 // declare the variable age
 
 if(age>=18){
 document.write("You are old enough to vote."); // this message only displays if age is greater than or equal to 18
 }
 
 /* Operators you can use include:
 == equal to
 != not equal to
 > greater than
 < less than
 >= greater than or equal to
 <= less than or equal to
 */
 
 </script>
 
</head>
<body>
 
</body>
</html>

Finding the length of arrays (and strings)

Sometimes you might need to find out how many elements exist in an array (that is, the length of the array). The sample code below shows exactly how to do that, and it also shows you how to find the length of a string using pretty much the same method.

The video here also explains how to do this.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - More Arrays</title>
 <script type="text/javascript">
 
 var cars = new Array();
 
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // to find the length (number of elements) of an array we can use arrayname.length eg.:
 
 document.write(cars.length);
 
 /* 
 We could also use the length method on a string like this:
 
 var word = "hello";
 document.write(word.length);
 
 */
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Arrays

Arrays are very useful in any programming language. When you use a simple variable, you can only store one value. For example age = 17 or name = “Harry”. But what if you want to store a list of related values such as all the names of members in a family? That is where arrays come in handy. Take a look at the syntax in the sample code below and make sure you watch the video on how to use arrays here, and also the video on finding the length of arrays and strings here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Arrays</title>
 <script type="text/javascript">
 
 // how to declare and initialise an array when you know the values
 var words = new Array("hello","hi","howdy","gday");
 
 // how to print an element from an array
 document.write(words[2]);
 
 // you can also declare an array by specifying the number of elements in the array without adding them eg.
 var pets = new Array(4);
 // and then add values later eg.
 pets[0]= "dog";
 pets[1]= "cat";
 pets[2]= "fish";
 pets[3]= "bird";
 
 // you can also start off with an empty array eg.
 
 var cars = new Array();
 
 // and then add values later
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // Some array hints:
 // each value is an element in an array
 // array elements are accessed using an index which starts from 0
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Variable scope

Now that you are using functions in JavaScript, it is really important to understand variable scope. JavaScript has two variable scopes: global and local.

  • A global variable is a variable which is declared outside a function and its value can be accessed and modified throughout your program
  • A local variable is a variable which is declared inside a function definition. It is created and then destroyed every time the function runs, and cannot be accessed or modified from outside the function.

Make sure that you watch the video on variable scope here to see how it works. Sample code is available for you to try out below.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Variable scope</title>
 <script type="text/javascript">
 
 // A local variable is defined inside a function and can only be used inside a function it's declared in
 // A global variable can be used anywhere in the program
 
 var name = "Smith"; //global variable
 
 function printName(){
 document.write(name + " inside function<br/>");
 // the name variable is being used inside the function
 }
 
 printName(); // this will run the printName function
 
 document.write(name + " outside of function<br/>"); // this uses the name variable outside of the function
 
 function printName2(){
 var name2="Mary"; // name2 is a local variable created inside this function
 document.write(name2 + " inside function<br/>");
 }
 
 printName2(); // this will run the printName2 function
 
 // what will happen when the line of code below runs?
 document.write(name2 + " outside of function<br/>");
 // the statement on the line above will not work because the variable name2 cannot be accessed outside of the function
 // If you go to the JavaScript Console in your browser, you will see an error has been reported when running the code
 // The error will look like: Uncaught ReferenceError: name2 is not defined
 // This error occurs because name2 can only be used by the printName2 function, and not outside the function.
 
 </script>
 
</head>
<body>
 
</body>
</html>

Functions with more than one parameter

In the previous sample code, we looked at how to use a parameter in a function. This sample code shows how to use multiple parameters. Make sure you also watch the video that explains functions and parameters here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Functions with multiple parameters</title>
 <script type="text/javascript">
 
 // define the function and set the parameters separated by comma
 function addNumbers(num1, num2){
 // function code goes here, eg:
 var answer = num1 + num2;
 document.write(answer + "<br/>");
 }
 
 // call the function three times with different parameters
 addNumbers(2,6);
 addNumbers(3,1);
 addNumbers(30,14);
 // notice that there is a <br/> tag in the function, so a new line will be added each time the function is called
 
 </script>
 
</head>
<body>
 
</body>
</html>

Functions with a parameter

The sample code shows how to make a function which uses a parameter.  A parameter is like a special variable which is used in a function to refer to a piece of data which is provided as input to the function. These pieces of data are also often called arguments.

The code below shows how to use just one argument. If you want to use more than one argument, see the sample code here. You can also watch the video which explains functions and parameters here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Functions with parameters</title>
 <script type="text/javascript">
 
 /* functions can also use one or more parameters
 a parameter is like a special variable which is used in a function to
 refer to a piece of data which is provided as input to the function. These pieces of
 data are also often called arguments.
 */
 
 // define the function and set the parameter eg. message
 function saymessage(message){
 // function code goes here
 alert(message);
 }
 
 // call the function to be used and provide "Hello world" as an argument to the function.
 saymessage("Hello there");
 </script>
 
</head>
<body>
 
</body>
</html>

Functions

Functions allow you to write lines of code that can be used again and again in different parts of a program without actually having to write the lines of code several times. You can create a function that runs some lines of code (usually a specific set of instructions) and then ‘call’ that function to be used later on. Have a look at the sample code below and make sure you watch the video here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Functions</title>
 <script type="text/javascript">
 
 // This is how you define a function
 function saymessage(){
 // function code goes here
 // more function code goes here
 // example of simple function code below:
 alert('Hello world');
 }
 
 // this is how you 'call' the function
 saymessage();
 
 //or you can call the function from an event like in a form, in the body section below
 </script>
 
</head>
<body>
 <form>
 <input type="button" value="click me" onclick="saymessage();"/>
 </form>
 
 
</body>
</html>

Events

This sample code snippet shows how to work with events (eg. onclick and onmouseover). It also shows how to use those annoying alert messages…but please, only use them for good! You will also be introduced to HTML form elements such as buttons.

Make sure you also check out the video here which explains how to use some of the other event types.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Events</title>
 <script type="text/javascript">
 
 // alert("Welcome to my web page"); would bring up an alert whenever the page loads
 // However, we will use a click event to load an alert message instead, and this will be in the body section of the html page
 
 </script>
 
</head>
<body>
 <form>
 <input type="button" value="click me" onclick="alert('You clicked me');"/>
 <input type="button" value="hover me" onmouseover="alert('You hovered over me');"/>
 
 </form>
 
 
</body>
</html>

Strings

Quite a lot is going to be covered in the source code snippet below. You might want to watch the video which explains all about working with strings by clicking here.

The sample code snippet below shows how to join (concatenate) strings, find the length of a string (the number of characters in a string), convert from integer to string, display specific characters in a string, split a string up and place each word in a separate array element, and convert string to uppercase and lowercase.

Don’t try all of this in one go. Have a go at one string operation at a time and only move on to the next one when you feel comfortable to.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Strings</title>
 <script type="text/javascript">
 
 var firstName = "Nicolas";
 var lastName = "Cage";
 
 // Concatenation means joining (eg. joining two strings together to form one string
 // Below, is an example of a concatenated string being held in a variable
 var joinednames = firstName + lastName;
 
 // Below, is an example of concatention with spaces added between words.
 document.write(firstName,' ',lastName,' ',"says \"hello\".");
 
 var fullName = firstName + ' ' + lastName; // this combines two variables and a space between the strings into a new variable
 
 document.write(fullName)
 
 var nameLength = fullName.length; // this calculates the length of the string as an integer
 document.write(nameLength);
 
 var age = 20;
 document.write(fullName + age); // this prints the name string and then the variable (no spaces) 
 
 var ageString = age.toString(); // this converts the age integer variable to a string variable
 document.write(ageString);
 
 /* To convert a string to an integer, the variable must firstly contain ony numbers. It can simply be multiplied by 1 to convert to an integer
 eg. newIntVariable = stringVariable * 1
 or you can use parseInt and parseFloat functions eg parseInt('77');
 */
 
 var message = 'Hello world!';
 document.write(message.indexOf('w')) // the indexOf function finds the index number of a character in a string
 document.write(message.charAt(8)) // this gives the character at index number 8
 document.write(message.length) // this will give the length of the string
 
 var messageArray = new Array();
 messageArray = message.split(' '); //this splits the words (where there is a space) into a new array
 document.write(messageArray[0],"</br>"); // this would return "Hello" (and a new line)
 document.write(messageArray[1]); // this would return "world!"
 
 document.write(message.substring(4,8)); //this will show anything between index number 4 and 8
 document.write(message.substr(4,8)); //substr is different to substring. this will show the 8 characters after index number 4.
 
 document.write(message.toUpperCase()); // converts string to uppercase
 document.write(message.toLowerCase()); // converts string to lowercase
 document.write("<b>",message.toUpperCase(),"</b>"); // this prints the uppercase string in bold using the HTML bold element <b>
 document.write("<h1>This is a heading</h1>"); // HTML elements can be put straight into a string
 </script>
 
</head>
<body>
 
 
</body>
</html>

Operators

If you have created your own variables and assigned them each a value (such as a string or integer), then you will already be familiar with the assignment operator which is a single = (equals sign).

There are other operators used for calculations though such as adding, subtracting, multiplying, dividing, increasing and decreasing values, etc. Take a look at the source code to see what is available.

Make sure you also watch the video about operators here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Operators</title>
 <script type="text/javascript">
 var x = 5, y = 10; //variables can be initialised on one line, separated by commas
 var z = x + y; // this is how variables can be added
 
 z++ //this increases the z variable value by 1
 
 z-- //this decreases the z variable value by 1
 
 // operators include + (plus) - (minus) * (multiply) / (divide) and % (modulus) which returns the remainder from division
 
 x+=y; //this is an example of compound addition. It is the equivalent of x = x + y
 // variables can be added using the compound addition += , compound subtraction -= , compound multiplication *= or compound addition /=
 
 document.write(z); // now let's see what the z variable displays after these modifications.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>