Introduction to JavaScript

As a developer, JavaScript can initially seem difficult, but learning the basics can be a really useful introduction. In this tutorial, I will guide you through a very basic introduction of programming in JavaScript to get you started.

JavaScript is a high-level, dynamic programming language to make web pages interactive. JavaScript is part of the ECMAScript language specification and is the language used in: Angular, Ember, React and Node.js to name but a few examples.

JavaScript files use the file extension .js

Comments

Comments are used to explain what your code is doing or to prevent code from being executed. It is always recommended to add comments to your code to help you to remember what you’ve done or to help explain to other developers how your code works.

Below are examples of comments that can be used within your code:

// A single line comment for a variable
var quantity = 6;
var additem = 2;
/*
A multi-line comment
over multiple lines
to describe the code below
*/
var total = quantity + additem;

Adding comments before a line of code will prevent it from being executed.

Variables

Data or information that needs to be temporarily stored within JavaScript can use a variable. Before a variable can be used, it needs to be declared (created). To declare a variable, we use the keyword of var followed by the name of the variable.

In the code example below, a variable named quantity is declared.

var quantity;

Once a variable has been declared, a value can then be assigned to it. Until a variable has a value, it is said to be undefined. A value is assigned to a variable using the assignment operator (=).

A value will now be assigned to the variable.

var quantity = 6;

Our first variable has been created. We will now add two further variables to perform a simple calculation.

var quantity = 6;
var additem = 2;
var total = quantity + additem;

The position where the variable is declared within the script is called the scope.

Strings are text values and are written in single or double quotes. If a number is written inside quotes, it will be treated as a text string. Numbers are written without quotes, as this example below demonstrates:

var pi = 3.14;
var largeNumber = 1028;
var firstName = "Dan";
var occupation = 'Web Developer';

Array

An array is similar to a variable, but can contain multiple values at any one time and should be used when working with a list or a set of related values. When creating an array, the array literal method is preferred over the array constructor method. You do not need to specify how many values the array will contain and values contained do not need to be the same data type.

I will create a simple array to hold a list of colours.

var colour = ['red', 'white', 'blue'];

Each item in the array is given an index number. The first value in an array always has an index of zero therefore, this type of array is called an indexed array.

For example, should you wish to access the colour blue from the array, the array name is specified along with the index number of the value you want to retrieve. In this example the index number is two.

var colour = ['red', 'white', 'blue'];
colour[2];

Each array has a property called length which counts the number of values within the array. In the example below, the property will return the length as three as the array contains three colour values.

var colour = ['red', 'white', 'blue'];
colour.length;

Values within an array can also be sorted into the correct order using the sort method.

var colour = ['red', 'white', 'blue'];
colour.sort();

I now have the colour yellow I wish to add into my array. To add the new colour, I can simply use the push method.

var colour = ['red', 'white', 'blue'];
colour.push('yellow');

Functions

A function is a block of code created to perform a specific task and executed when invoked (called). Functions are declared (created) using the function keyword followed by the name of the function. The name of the function is often called the identifier. The statements or group of statements that perform the task are placed within the code block of the function.

Functions allow code to be written once and reused multiple times.

function myFunc() {
// This is a code block
}
myFunc();    // Call the function

Sometimes a function needs specific information to perform its task. To do this we use parameters and arguments. When the function is declared, it is given parameters. These act like variables and are placed within the parenthesis (curly braces) that follow the function name.

function getArea(parameter) {
}
getArea(argument);

The values specified in the parameters are called arguments and can be provided by values or as variables.

Here is an example function to calculate the area of a shape using parameters and arguments.

function getArea(width, height) {
return width * height;
}
getArea(3, 5);

We can also use variables to specify the width and height values.

function getArea(width, height) {
return width * height;
}
var shapeWidth = 3;
var shapeHeight = 5;
getArea(shapeWidth, shapeHeight);

Functions may return information to the code that called them using the return statement/keyword. When return is used, the interpreter leaves the function and goes back to the statement that called the function.

We can use functions to return more than one value, using an array. The code example below, calculates both the area and volume of a shape. The area of the shape is stored in a variable called area and the volume is stored in a variable called volume. Both variables are then placed into an array called sizes, which is returned to the code that called the function, allowing the values to be used.

function calculateSize(width, height, depth) {
var area = width * height;
var volume = width * height * depth;
var sizes = [area, volume];
return sizes;
}
// Array index is 0, so area will be calculated
var getArea = calculateSize(3, 2, 5)[0];
// Array index is 1, so volume will be calculated
var getVolume = calculateSize(3, 2, 5)[1];

How to apply JavaScript to HTML pages

To complete this introduction to JavaScript, I will create a simple HTML web page that will use JavaScript to display content onto the page.

Begin by creating a simple HTML web page named index.html with the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript example</title>
</head>
<body>
<div id="shape-area"></div>
<div id="shape-volume"></div>
<script src="shape.js"></script>
</body>
</html>

Once complete, open a new file named shape.js where the JavaScript code below will be placed:

function calculateSize(width, height, depth) {
var area = width * height;
var volume = width * height * depth;
var sizes = [area, volume];
return sizes;
}
// Array index is 0, so area will be calculated
var getArea = calculateSize(3, 2, 5)[0];
// Array index is 1, so volume will be calculated
var getVolume = calculateSize(3, 2, 5)[1];
// Output the area and volume to the HTML web page
document.getElementById("shape-area").innerHTML = getArea;
document.getElementById("shape-volume").innerHTML = getVolume;

If successful, you should see the number 6 and 30 displayed within your HTML web page displaying the area and volume values from the JavaScript function.