Back

JavaScript Basics

This is a basic introduction to the JavaScript computer language.

JavaScript is now one of the most popular and useful computer languages on the planet. It can be used to create web pages, web servers, mobile Apps and even inside embedded micro-controllers!

Statements

JavaScript 'Apps' are computer programs written as lines of text. Each line of text is made up of one or more statements, which are separated by a ';' (semi-colon) character like this:-

   statement1;
   statement2;
   statement3;

These statements contain instructions for the computer to perform (execute) and the ';' character at the end tells the computer where each statement ends and the next one starts.

We usually place statements on separate lines as this can help when looking for bugs (problems). Here's a simple JavaScript program made using two statements. It displays the word "Hello" in a popup box:

   var s = "Hello";
   alert( s );

Comments

You should also add comments to your programs, which are ignored by the computer but help you and others understand what the program is supposed to be doing. To do this you use the '//' (double forward slash) characters.

For example we can add a comment line to the program above:

   //This shows a popup message.
   var s = "Hello";
   alert( s );

Variables

Variables are declared using the 'var' keyword and allow us to store data such as text, numbers and objects in the computer's memory using a name of our choosing. We can then read and change the stored data later by using the name we have given to the variable.

We can store text and display it like this:

   //This shows the message 'Hi'.
   var myText = "Hi";
   alert( myText );

Note: Text data should always be enclosed in quotes or the computer will think it's a variable name.

We can store a number and then display it like this:

   //This shows the message '7'.
   var myNum = 7;
   alert( myNum );

We can change the contents of our variables like this:

   //This shows the message '6'.
   var myNum = 3;
   myNum = myNum * 2;
   alert( myNum );

Note: JavaScript is case sensitive, so myNum is not the same MyNum.


Expressions

A statement such as myNum = myNum + 2 is an expression and we can perform various maths and text operations on our variables using expressions.

For example:

   //This shows the message 'Answer: 17'.
   var myNum = 7;
   var myText = "";
   myNum = myNum * 2 + 3;
   myText = "Answer: " + myNum;
   alert( myText );

Note: When you add a number to text, the number is automatically converted to text.


Data Types

In JavaScript, we can store and use these data types:

   String - Text data.
   Number - Numbers.
   Boolean - True or false values.
   Array - Lists of data.
   Object - Complex data types.

We can store all of these types in variables and also use them in expressions, but the Array and Object data types are special 'reference' types, which means variables containing these types actually hold a reference (or pointer) to the original data rather than the actual data.

When you copy reference types from one variable to another, you will not get a separate copy of the data in the computer's memory, but rather a copy of the reference.

Here are a few examples of using various data types:

   //This shows the message 'true'.
   var isGood = true;
   alert( isGood );
   //This calculates a circle's circumference.
   var pi = 3.14;
   var r = 5;
   alert( 2 * pi * r );
   //This shows the message 'Hello World'.
   var s = "Hello";
   alert( s + " World" );
   //This shows the message 'First item: 3'.
   var myArray = [3,4,5];
   var firstItem = myArray[0];
   alert( "First item: " + firstItem );
   //This shows the message 'First item: fred'.
   //(Arrays are reference types).
   var myArray1 = ["a","b","c"];
   var myArray2 = myArray1;
   myArray1[0] = "fred";
   alert( "First item: " + myArray2[0] );

Conditional Statements

We often want to take different actions in our program depending on certain conditions and the easiest way to do this is using an 'if' statement like this:
    if( x > 1000 ) splat = true;
The line of code above would set the variable 'splat' to true if the variable 'x' contains a value greater than 1000. We can also use the 'else' statement in combination with 'if' statement to do one thing or the other:
    if( splat ) image = "splat.jpg";
    else image = "bird.jpg"; 
If we want to check a whole lot of conditions, we can do something like this:
  //Find the correct photo.
  if( name=="Sam" && male ) image = "Samuel.jpg";
  else if( name=="Sam" ) image = "Samanther.jpg";
  else if( name=="Bill" ) image = "William.jpg";
  else image = "Anyone.jpg"; 

Note: We use the double equals sign when we comparing variables and the single equals sign when we are assigning (setting) variables.

In order to execute more than one statement after an 'if' or 'else' clause, we can use the '{}' (brace) characters to group statements into a 'block' of code:

For example, in a game we might have some statements like this to check if the character has crashed and the game is over:

    if( splat ) 
    {
        imageName = "splat.jpg";
        gameOver = true;
    }
    else 
    {
        imageName = "bird.jpg"; 
        gameOver = false;
        count++;
    }

Operators

We can perform various mathematical, logical and text operations in JavaScript such as add, subtract, divide and multiply but you will often see a statement like this:

    num += 2;
This may look confusing at first, but this '+=' operation simply adds 2 to the contents of variable 'num'. This is a shorter and more efficient way of writing the following:
    num = num + 2;
Here are some examples of the most common operations and their meanings:
 z = x * y;      //z = x multiplied by y
 z = x / y;        //z = x divided by y
 z = x % y;      //z = remainder of x divided by y
 num++;         //add 1 to the contents of num
 num--;          //subtract 1 from contents of num
 num += 3;     //add 3 to the contents of num
 num -= x;     //subtract x from contents of num
 num *= 9;     //multiply the contents of num by 9
 num /= 9;     //divide the contents of num by 9
 b = 7;           //set b to the value 7
 if( b == 4 )    //if b is equal to 4
 if( b != c )     //if b is not equal to c
 if( b > c )      //if b is greater than c
 if( b < c )      //if b is less than c
 if( b >= c )    //if b is greater or equal to c
 if( b <= c )    //if b is less than or equal to c
 if( b || c )     //if b or c is true
 if( b && c )   //if b and c are true
 if( b && !c )  //if b is true and c is false

Another very useful operation is the ?: or 'Ternary' operation. This allows us to conditionally get one of two possible values using a single line of code. For example:

    adult = (age > 18 ? true : false);

This is the same as writing:

    if( age > 18 ) adult = true;
    else adult = false;

You can use this in expressions too. Here's another example:

 meals = 7 * (name=="Sam" ? 6 : 3);

Loops

In JavaScript we often want to repeat a block of statements many times and the two most common ways of doing this are with the 'while' and 'for' statements.

A 'while' statement will keep repeating a block of statements while a given expression is true. For example, the following code will keep asking the user if they are ready until they answer "yes".

    var answer;
    while( answer != "yes" )
    {
        answer = prompt( "Are you ready?" );
    }
A 'for' statement is usually used to repeat a block of statements until a counter has reached a certain value. The following code will add the letter 'O' to the letter "G" ten times, followed by the letters "GLE".
    var txt = "G";
    for( var i=0; i<10; i++ )
    {
        txt += "O";
    }
    txt += "GLE"
    alert( txt );

In the above sample, the counter variable 'i' starts at zero and increases by 1 each time the block of code is complete, but only while 'i' contains a value less than 10. So the variable 'i' will range from zero to nine.


Functions

If we find that we need to execute the same (or a similar) group of statements from various parts of our program, then instead of copying and pasting the same group of statements all over our program, it is far more efficient and much neater to 'wrap' a block of code up using the 'function' statement. We can then use a single line of code to 'call' our function and execute the block of code.

For example, if we needed to show a random number to the user and we expect to do that more than once in our program, then we could define a function called 'ShowRandom' and call it like this:

    //Show a random number.
    function ShowRandom()
    {
        var num = Math.random();
        alert( num );
    }
    
    ShowRandom();
If we want the function to behave slightly differently each time we call it, then we can pass input values to the function. These are known as input 'parameters'.

So for example we might want to change the range of the random numbers produced by our 'ShowRandom' function by providing a 'range' parameter like this:

    //Show a random number in a given range.
    function ShowRandom( range )
    {
        var num = Math.random() * range;
        alert( num );
    }
    
    ShowRandom( 10 );
    ShowRandom( 100 );

As well as using input values, we can also get an output ('return') value from our function too, by using the 'return' statement. This allows our function to do calculations based on the input parameters and return a result afterwards.

We could for example create our own function to calculate the area of a circle like this:

    //Get the area of a circle.
    //(to two decimal places)
    function GetAreaOfCircle( radius )
    {
        var area = Math.PI * radius * radius;
        return area.toFixed(2);
    }
    
    //Show area of a circle with radius 4.8cm
    var area = GetAreaOfCircle( 4.8 );
    alert( "Area = " + area + " cm" );
In Javascript we don't have to place our function before the statement which uses it, so we can put it at the bottom of our script if we prefer, like this:

    //Show volume of box 4cm x 4cm x 2cm
    var vol = GetVolumeOfBox( 4 ,4, 2 );
    alert( "Volume = " + vol );
    
    //Get the volume of a box.
    function GetVolumeOfBox( width, height, depth )
    {
        var volume = width * height * depth;
        return  volume;
    }

String Handling

We often want to manipulate strings (text) in JavaScript and there are a number of useful methods available to us for doing this. Note that the position of characters within a string (known as their 'index') always starts at zero.

One of the most useful string methods is the 'split' method. This allows us to split the string into parts and store each part in an array. The split method takes a single parameter which tells the computer which character to look for while splitting the string.

For example if we want to get the first and third names in a comma separated list of names, we do the following:

    //Get the first and third list items.
    var names = "Fred,Bill,Amy,Sally";
    var namesArray = names.split(",");
    var firstName = namesArray[0];
    var thirdName = namesArray[2];

Another very useful string method is the 'indexOf' method. This allows us to find the index (position) of a string within another string.

For example, we might want to check if a file is a text file by searching for the string '.txt' in its file name like this:

    //Check for text files.
    var isTextFile = false;
    if( fileName.indexOf(".txt" ) > -1 ) 
        isTextFile = true;

Here are some more examples of the many string manipulation methods available to us in JavaScript:

   //Set our test string
   var txt = "Big Friendly Giant";
   
   //Get the number of characters in the string.
   var numLetters = txt.length;
   
   //Get a copy the first character.
   var firstLetter = txt.slice( 0, 1 );
   
   //Get a copy the last character.
   var lastLetter = txt.slice( -1 );
   
   //Get a copy the first word.
   var firstWord = txt.substring( 0, 3 );
   
   //Get a copy of the second word.
   var secondWord = txt.substring( 4, 12 );
   
   //Get the start index of the word 'Giant'.
   var indexOfGiant = txt.indexOf( "Giant" );
   
   //Get the start index of the word 'Big'.
   var indexOfBig = txt.indexOf( "Big" );
   
   //Get the index of the last space.
   var indexOfLastSpace = txt.lastIndexOf( " " );
   
   //Get a copy of string with word replaced.
   var changed = txt.replace( "Big", "Little" );
   
   //Get a lower case copy of the string.
   var lowerCase = txt.toLowerCase();
   
   //Get an upper case copy of the string.
   var upperCase = txt.toUpperCase();
   
   //Split the string into an array of words.
   var arrayOfWords = txt.split(" ");