JavaScript Tutorial for Absolute Beginners (GCSE & A Level)

Welcome to the world of JavaScript, the language that brings websites to life! This beginner-friendly tutorial is your one-stop shop to learn the fundamentals of coding interactive web pages, perfectly tailored for GCSE and A Level students.

Whether you're new to programming entirely or want to solidify your understanding for exams, this guide will take you step-by-step through core concepts like variables, decision making, and loops. You'll not only grasp the theory, but also build practical projects to solidify your skills and impress your teachers.

Let's dive in and get you coding in minutes!

All you need is the humble NotePad that comes free with your Windows Operating System by Microsoft.

notepad saving

 

Open NotePad and then open a new document, save it on the Desktop as First_page.htm.

Now, type in the following code and save it. It is your first HTML page. Then highlight the document and press F5. You will see your first web page.

As you can see, this is a plain web page. In order to make it more dynamic and interactive, we use JavaScript.

Type in the following code within <head></head> tags:

<html>
<title>XHTML by Vivax Solutions</title>
<head>
<script type="text/JavaScript">
alert('Welcome to Vivax Solutions');
</script>
</head>
<body>
</body>
</html>

Now press F5 and refresh your web page. You will get the following alert - and you ran the first JavaScript script successfully.

alert box

 

JavaScript commands must be written between <script></script>tags, as it is a script language. alert is a JavaScript command that produced the message as an alert. Please note the following:

  1. 1) JavaScript is case sensitive
  2. 2) JavaScript commands must end with a semi-colon

JavaScript commands can be used to write things as the content of a web page. Follow the following script and its corresponding output:

writing to document

 

<html>
<title>My First Web Page</title>
<head>
</head>
<body>
<script type="text/JavaScript">
document.write('My first web page is this. <br />It is pretty simple and plain');
</script>
</body>
</html>

Note the position of <br /> tag. It helps start a new line whenever we need one.

User Interaction

<html>
<title>My First Web Page</title>
<head>
</head>
<body>
<script type="text/JavaScript">
var age = prompt('How old are you?', 50);
document.write('You are ' + age + ' years old.');
</script>
</body>
</html>

age is a variable - a sort of container to hold a value. prompt command offers the user with an opportunity for an input.

If user enters a value it will be stored in age. Otherwise, it will use 50, the default value as the input.

Then, the value will be written on the web page. The sequence of execution is as follows:

prompt

 

prompt command and confirm command in JavaScript go hand in hand. The latter give the user an opportunity to confirm or refuse what was given in the form of a prompt.

The following script and the corresponding image that follows show the steps in the execution:

<html>
<title>My First Web Page</title>
<head>
</head>
<body>
<script type="text/JavaScript">
var x = confirm('Confirm your age.');
if(x==true)
{
document.write('You confirmed your age.');
}
else
{
document.write('You denied your age.');
}
</script>
</body>
</html>

confirm

 

Note the use of if and else elements in the script in making a decision based on what is stored on a variable.



Functions

A function is executed to perform a a specific task, when a user needs one; it takes the following form:

function(param1, param2)
{
code goes here
}
where param1 and param2 are the two arguments of the functions.
The user have to submit the two - or more - values when the function needs to perform its task.
Please note the code must be written between the two {} brackets.

E.g.

If a user wants to find the volume of a cylinder, the following function can be used. The two variables are the radius and the height, which store the values that come from the two text boxes.

function Vol_of_Cylinder()
{
var radius = document.getElementById("T1").value;
var height = document.getElementById("T2").value;
var vol = Math.round(3.142 * radius * radius * height*100)/100;
alert('Volume of the Cylinder = ' + vol);
}
The vol is also a variable - var - which retains the calculated value of volume. Then it returns this value when function is called with the submission of radius and height.

  • document.getElementById("Textbox ID").value fetches the data from the text boxes to be stored in the relevant variables.
  • Math.round is a function of JavaScript library which can round up values to integers.
  • alert is also a JavaScript function that displays the final result.

Let's see this function at work.

Radius:   Height:

 

 

The HTML code of the programme is as follows:

Radius: <input type="text" class="centralized" id="T1" size="5" /> &nbsp;&nbsp;Height: <input id="T2" type="text" class="centralized" size="5" />
<input id="Button1" type="button" value="Click to find the Volume" onclick="Vol_of_Cylinder()" />

In order to call the function, we use onclick event of the button.

Of course, the function is far from perfect, although, it does the job. What would happen, if someone clicks the button without entering radius or height or both? It leads to an error. The following revised line of code will deal with it effectively.

function Vol_of_Cylinder()
{
var radius = document.getElementById("T1").value;
var height = document.getElementById("T2").value;
if (radius == "" || height == "")
{
alert("Enter the values, please");
}
else
{
var vol = Math.round(3.142 * radius * radius * height * 100) / 100;
alert('Volume of the Cylinder = ' + vol);
}
}

If radius and height are not entered, an alert box crops up to warn against the move by the user. if -else - condition takes care of it.

A function can be defined with two or more arguments. When such a function is called, the arguments must be provided in the form of parameters.

The following function, Average has five arguments. So, if you want to use them those five arguments must be given to the function so that it will return a value.

function Average(num1, num2, num3, num4, num5)
{
var ave = (numb1 + num2 + num3 + num4 + num5) / 5;
return ave;
}

The average of 12, 8, 6, 9, 15 is produced by this function can be seen by clicking the button.



To get the function work, the onclick event of the button must be used as follows:

<input id="btnAverage" type="button" value="Click this to get Average"
onclick="this.value='Average = ' + Average(12,8,6,9,15);"/>

Please note the position of Average() function within onclick event handler.

Random Number Generator

Click the button to generate random numbers in the text box.

  

The function is as follows:

function Rndm_Number()
{
var a = Math.round(Math.random()*100+1);
document.getElementById("txtRandom").value = a;
}

Then call the function through the onclick event of the button as follows:

<input id="Button6" type="button" value="Get Random Numbers"
onclick="Rndm_Number()" />  <input id="Text1" type="text" />

The programme generates a random number between 1 - 100 by using Math.random() method and Math.round() method of Math object.

Odd Even Checker

 

  

 

The function, Odd_Even(), is as follows:

function Odd_Even()
{
var a = document.getElementById("txtOddEven").value;
var b = a % 2;
if(b==0)
{
document.getElementById("txtOddEven").value = "It is Even";
}
else
{
document.getElementById("txtOddEven").value = "It is Odd";
}
}

The onclick event of the button calls the function to test what is in the text box.

<input id="btnOddEven" type="button" value="Enter the Number and then Click"
onclick="Odd_Even()" />  <input id="txtOddEven" class="centralized" type="text" />

Advanced Functions

The following examples use JavaScript to perform more advanced tasks.

Getting Head or Tail

This programme simulates the tossing of a coin. Two randomly generated numbers are used to load two images of a coin, depending on the random values - 1 or 2 with 1 for a Head and 2 for a Tail

coin
HeadTailTotal
     

 

There are two functions at work in this programme:

  • the function, Head_Tail to get the relevant image loaded
  • the function, Head_Tail_Clear to clear the text boxes

There are two images to represent the Head and Tail - kasi2.gif and kasi1.gifThe JavaScript code for the two function is as follows:

function Head_Tail()
{
//get two random numbers - 1 and 2
var x = Math.round(Math.random() * 2 + 1);
// If it is 1, execute the code to load Head
if (x == 1) {
// Get the value stored in a hidden text box to increase the count of heads
var y = Math.round(document.getElementById("h1").value);
y = y + 1;
document.getElementById("h1").value = y;
document.getElementById("coin").src = "../images/kasi2.gif";
document.getElementById("txtHead").value = y;
}
// If it is 2, execute the code to load Head
else {
// Get the value stored in a hidden text box to increase the count of tails
var z = Math.round(document.getElementById("h2").value);
z = z + 1;
document.getElementById("h2").value = z;
document.getElementById("coin").src = "../images/kasi1.gif";
document.getElementById("txtTail").value = z;
}
// Get the value stored in a hidden text box to increase the total count
var j = Math.round(document.getElementById("h3").value);
j = j + 1;
document.getElementById("h3").value = j;
document.getElementById("txtTotal").value = j;
}

function Head_Tail_Clear()
{
// clear text boxes and the values in the hidden text boxes
document.getElementById("txtHead").value = "";
document.getElementById("txtTail").value = "";
document.getElementById("txtTotal").value = "";
document.getElementById("h1").value = "";
document.getElementById("h2").value = "";
document.getElementById("h3").value = "";
}

Compound Interest Calculator

The following programme calculates the value of a deposit after every year, if the compound interest added to the principal amount after the end of every year.

P - principle amount; n - number of years; r = interest

Pnr

 

   

 

There are two functions at work in this programme:

  • the function, Comp_Amount to calculate the amount of money paid to the account
  • the function Comp_Clear to clear the text boxes

The JavaScript code for the function is as follows:

function Comp_Amount() {
var xx = document.getElementById("txtPrincipal").value;
var yy = document.getElementById("txtInterest").value;
var zz = document.getElementById("txtYears").value;
var xyz = xx * Math.pow((1 + (yy / 100)), zz);
document.getElementById("txtAmount").value ="£ " + Math.round(xyz * 100) / 100;
}

function Comp_Clear() {
document.getElementById("txtPrincipal").value = "";
document.getElementById("txtInterest").value = "";
document.getElementById("txtAmount").value = "";
document.getElementById("txtYears").value = "";
}

16-million Colour Maker

Each colour you can think of is just a combination of three colours. They are called primary colours. The three primary colours are:

  • Red
  • Green
  • Blue

The following programme lets you make any colour you can think of by mixing the three primary colours in various proportions. You can enter the values for Red, Green and Blue - a number less than 255 - and make various colours. That is how modern computers produce millions of colours using the three primary colours. Thanks to this little programme, you can have some fun too.


RedGreenBlue
Watch this space
   

 

The above programme uses two functions: the function, mix(), makes the colours from the primary colours; the function, Resetting(), clears the text boxes. The two functions are as follows:

function Cmix() {
// if no value is entered, alert the user
if (document.getElementById('TOne').value == "" || document.getElementById('TTwo').value == "" || document.getElementById('TThree').value == "") { alert('Please fill in all the boxes') }
else {
// get the values
var x = eval(document.getElementById('TOne').value);
var y = eval(document.getElementById('TTwo').value);
var z = eval(document.getElementById('TThree').value);
if (x > 255 || y > 255 || z > 255)
{ alert('Enter a number less than 256 please!') }
else {
// colour the button
document.getElementById("clrbtn").style.backgroundColor = "rgb(" + x + "," + y + "," + z + ")";
document.getElementById("clrbtn").style.color = "#fff"
}
}
}
function Resetting() {
// reset the colour button
document.getElementById("clrbtn").style.backgroundColor = "#fffacd"
document.getElementById("clrbtn").style.color = "#000"
}

Quadratic Solver

A quadratic equation takes the form of ax2 + bx + c where a and b are two integers, known as coefficients of x2 and x respectively and c a constant.

Enter a, b and c to find the solutions of the equations.

E.g.

x2 - x - 6 = 0 where a = 1; b=-1; c=-6

abc

 

The code is as follows:

function Quad_Solve() {
//get the values of a, b and c
var a = document.getElementById("txtA").value;
var b = document.getElementById("txtB").value;
var c = document.getElementById("txtC").value;
var d = b * b - (4 * a * c);
// check whether the discriminant is positve or negative
if (d < 0) {
document.getElementById("txtAns").style.color = "red";
document.getElementById("txtAns").value = "There are no real solutions.";
}
else {
// calculate the solutions
var e = (-b + Math.sqrt(d)) / (2 * a);
var f = (-b - Math.sqrt(d)) / (2 * a);
document.getElementById("txtAns").value = "x = " + e + " or " + f;
}
}

function Quad_Clear() {
// clear the text boxes
document.getElementById("txtA").value = "";
document.getElementById("txtB").value = "";
document.getElementById("txtC").value = "";
document.getElementById("txtAns").value = "";
}

Palindrome Checker

A palindrome is a word, a number, a phrase or even a set of characters that reads the same, both forward and backward.

E.g.MADAM, 12321, NEVER ODD OR EVEN, TOPOT

This is a simple JavaScript function that tests whether a simple word is a palindrome or not.

 

    

 

The process is as follows:

  • The length of the string, the word, is taken.
  • Using the for-loop, the string is reversed and stored in a new variable.
  • Checking whether the two variables are the same.

The code is as follows:

function Palindrome() {
var x = document.getElementById('txtPalindrome').value; // original string
var y = "";
for (var i = x.length - 1; i >= 0; i--) {
y += x[i]; // new string
}
if (x == y) {document.getElementById('txtPalindrome').value="It's a palindrome."}
else { document.getElementById('txtPalindrome').value = "It's not a palindrome." } }

 

setInterval and clearInterval functions

setInterval() function is a very useful function for animations. For instance, it can be used to create a countdown or an alarm or even a clock.

clearInterval() function, on the other hand, cancels the setInterval() function.

The setInterval() function takes two arguments - a function and time value in milliseconds. clearInterval() function takes one argument - the very function that executes setInterval() function.

In order to use setInterval() function in conjunction with clearInterval() function, the following example shows how a countdown is made with the aid of the functions.

 

var x = document.getElementById("btn");
var start-value = 10;
var y;
function runCountdown() {
  start-value -= 1;
  x.value = "Countdown: " + start-value;
  if (start-value == 0 || start-value < 0) {
    clearInterval(y);
    x.value = "Restart"
    start-value = 10;
  }
}
function countDown() {
 y = setInterval(runCountdown, 1000)
}

 

First of all, the button element is refereed to in a variable, x. Then, setInterval(runCountdown, 1000) function is called with two parameters in it - a function in which countdown variable is called at an interval of 1000 milliseconds or 1 second. It's stored in a variable, y, which in turn is in a function, countDown(). countDown() is attached to the click even of the button, 'Start Countdown'.
After 10 seconds or countdown is less than or equal to 0, the clearInterval() runs. As the only parameter required for the function, variable y - the very variable that calls setInterval() function is calling.

 

setTimeout and clearTimeout functions

Exactly like setInterval() function, setTimeout() is a very useful function for animations too. For instance, it can be used to create something to be activated at a given time in the future, set within a function. The function take two parameters - a function and time in milliseconds.

cleaTimeout() function, on the other hand, cancels the setTimeout() function.

The setTimeout() function takes two arguments - a function and time value in milliseconds. clearTimeout() function takes one argument - the very function that executes setTimeout() function.

In order to use setTimeout() function in conjunction with clearTimeout() function, please look at the following example; it shows how a countdown is made with the aid of the functions.

         

 

var xx = document.getElementById("btntwo");
var yy;
function greetNow() {
  xx.value = "Welcome!";
}
function greetings() {
 yy = setTimeout(greetNow, 5000)
}
function stopGreetings() {
 yy = clearTimeout(yy)
 yy = alert("It's stopped!");
}
function restoreGreetings() {
  xx.value = "Greet in 6 Seconds";
}

 

When the button,'Greet in 6 Seconds', is pressed, the message, "Welcome!" comes on the button after 6 seconds.You can still cancel the process before 6 seconds elapsed; you just have to call, clearTimeout() function. The very variable that stores the function should be used as the only parameter of the function.

If you want to restore the 'Greet in 6 Seconds' button, you just have to press, 'Restore' button.

 

Any comments? Please drop a line.