Getting Started with JavaScript

Who is this guide for?

This quick-start Javascript tutorial is inteded for new Javascript learners.

Some basic knowledge of HTML would be useful to follow along with the examples.

What is covered?

This tutorial covers the building blocks of using Javascript for web development:

  • Setting up a local development environment
  • Selecting, adding, removing and editing elements on a web page
  • Creating ‘event listeners’ to make a web page responsive to user input
  • Basic form validation techniques

In doing so, it introduces the following key programming technqiues:

  • Accessing the DOM
  • DOM manipulation
  • Creating event listeners
  • Functions
  • If/else conditional statements
  • Loops

This guide provides first examples and explanations for these concepts.

To master these concepts, it is important to practice them in real or practice projects and become familiar with more complex use cases. For the latter, links to further learning materials are embedded throughout the tutorial.

Contents

  1. Why learn Javascript?
  2. Getting started with Javascript
  3. Selecting HTML elements
  4. Adding an event listener
  5. Writing and executing a function
  6. Manipulating the DOM
  7. If/else conditional functionality
  8. Utilising a loop
  9. Conclusion

Why learn Javascript?

Learning Javascript will enable you to develop interactive and user-responsive website designs.

In frontend web development:

  • HTML provides the basic elements and content of a page
  • CSS is used to styles pages
  • Javascript is used to create interactive functionality

Though HTML and CSS can be used to produce good-looking pages, these can only take development so far. Javascript provides an extremely flexible and powerful tool to create dynamic pages that are responsive to user actions.

For example, in response to a user click, we may want to display more information (e.g. about a product) or trigger an alert (e.g. “Are you sure you want to proceed?”) to warn a user before executing an action. It is exactly for the programming of such important events that Javascript is designed!

Though it is technically possible to achieve these same results using other programming languages, Javascript holds a priviliged position in web programming because it is supported by all modern web browers. As such, when writing Javascript, you can be confident it will work as you intend for your end-user. This makes Javascript an insanely popular language amongst web developers!

Due to this popularity, there is a highly active online Javascript community, including plenty of free and paid resources that caters to learners of all levels. You will never need to be alone on your Javascript journey! (unless, of course, you want to be!).

Most popular programming, scripting and markups languages according to the Stack Overflow 2020 Developer Survey:
JavaScript 67.7%
HTML/CSS 63.1%
Python 44.1%
Java 40.2%
Bash/Shell/PowerShell 33.1%
C# 31.4%
PHP 26.2%
TypeScript 25.4%
C++ 23.9%

Javascript is also the syntactical foundation of popular frontend web frameworks, such React, Angular and Vue. Learning Javascript will make all of these much easier to learn!

You can even venture into backend programming with Javascript using the NodeJS framework, though Javascript is most widely used in frontend development.

Average earnings of a frontend web developer

On the basis of data from Glassdoor, below is the average earnings of a frontend web developer in the United States:

  • < 1 year experience: $71,640/yr
  • 1-3 years experience: $77,192/yr
  • 4-6 years experience: $82,610/yr
  • 1-3 years experience: $102,183/yr

Moreover, demand for frontend web developers has never been higher.

According to data from ITJobsWatch, the number of new frontend developer job postings as a percentage of all IT job postings has steadily increased over time, with a spike in demand now following the coronavirus pandemic.

Graph displaying a growth in the demand for frontend developers
Job postings data from ITJobsWatch.

There has perhaps never been a better time to learn Javascript! So let’s get started!

Creating a new work environment

As mentioned above, there is a divison of labour in web development, with HTML responsible for providing the basic structure of a webpage, CSS for styling, and Javascript for providing interactive functionality. As such, Javascript is not a tool to be used in isolation but in harmony with HTML and CSS. To do so requries the setting up a development enivornment in which Javascript can access the contents of a HTML-generated webpage.

One way of shortcutting this process is to use a pre-configured online environment such as CodePen or JSFiddle. Both of these are excellent ways to share your code online, but it is strongly advised to set up a local environment to follow this tutorial. It is important to get used to this way of working from the beginning, as this is how you would work on real projects.

To get started with Javascript, we could open notepad, start writing and save our work with the .js extension. This would be a valid Javascript file!

But this is not recommended. Instead, it is better to use an editor designed to handle Javascript (and HTML, CSS as well as other files). Code editing software provides several important advantages, such as color highlighting of code to make it more readable, predictive typing and cool plug-ins that provide you with access to a small universe of utilities! Free-to-use Visual Studio Code is a popular choice but there are many other options.

Linking Javascript to a HTML file

To start configuring your working environment, create a new folder on your local computer called “GettingStartedJS”. Now, open a new document in your code editor and write the basis for a (for the moment) blank HTML document. To save time, you can copy and paste the boilerplate code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

Now save this as index.html within the GettingStartedJS directory.

Next, we create the CSS file. To do this, again create a new file in your code editor, paste in the following code and save it as styles.css also in the GettingStartedJS directory.

body {
    background-color: #FFFFFF;
}

Finally, we create the Javascript file to link to the HTML file. We can do this by creating a new document and saving it with the .js extension.

Let’s copy and paste the following into the new document and save it as script.js.

// JS code goes here

Inside the GettingStartedJS there are now three documents: index.html, styles.css and script.js. But at the moment, they cannot ‘talk’ to each other as they are not aware of each others’ existence!

We can resolve this by making a couple of additions to our index.html document:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css"> <!-- * NEW CODE LINE 1 FOR CSS * -->
    <title>Document</title>
</head>
<body>

<script src="script.js"></script> <!-- * NEW CODE LINE 2 JAVASCRIPT * -->
</body>
</html>

First, we link our HTML file to our CSS file in line 7. This line tells the HTML document that styles.css will be used for styling. As it is in the same directory as index.html, it is not necessary to specify a file path.

Second we link to our Javascript file on line 12. Here, we tell our HTML document to load script.js after the body of our HTML document is loaded.

Once saved, that’s it! You are now able to use CSS to style and, most importantly, Javascript to edit the content of the web page.

To check it is working, copy and paste the following Javascript into script.js This code is only for testing purposes, so don’t worry if you do not understand it. After saving, open index.html. If Javascript is connected properly, you should see “Hi from index.js!” on the page. Note that this text is not created by index.html. Instead, it is created by script.js ‘reaching’ into the web pages and editing its code after index.html rendered an empty document.

var paragraph = document.createElement('h1');

paragraph.textContent = "Hi from script.js!";

document.body.append(paragraph);

We are now able to start learning how we can use Javascript to manipulate web pages in more practically useful ways. This process is most commply termed manipulation of the DOM.

Selecting HTML elements

Though a linked Javascript file has access to the DOM produced by the HTML file, it does not have access to the individual elements. These have to be selected.

To start selecting, let’s first create some basic elements inside the <body></body> tags of the HTML document.

We create a h1 element and assign this an ID of textToEdit and and input element with an ID of buttonToClick:

...
<body>
    <h1 id="textToEdit">Please click the button below (e.g. to submit some data)</h1>
    <input type="button" id="buttonToClick" value="Click me">

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

Clear your Javascript file of any content from the previous section.

When you save this and open index.html in your browser now, it should look something like this:

How index.html should look when opened in the browser

To load the h1 and input element into Javascript, we must first specify to Javascript that it should look amongst the HTML elements of the page to which it is linked by calling document and applying the method .getElementById(). This tells Javascript that we want to get an element within document (i.e. DOM) object by its unique ID. We specify the IDs of the elements we want to select by entering these in quotation marks within the .getElementById() method’s parentheses.

document.getElementById('textToEdit');
document.getElementById('buttonToClick');

This, however, does not save the selected elements anywhere. By the time we reach the second line of code, Javascript has forgotten about the element selected on the first line. And after the second line, it has forgotten about both. We need a way to store these selected elements and we can do this using variables.

We create a variable by writing var and the name of the variable followed by an equals sign. After the equals sign, we specify this content to be stored in the variable. In our case, our two selected elements:

var text = document.getElementById('textToEdit');
var button = document.getElementById('buttonToClick');

Both these elements are now available later in our script by either calling text or button.

Adding an event listener

With the two elements saved, we can now start to manipulate them.

In most cases, we want to make a page interactive in response to a user-generated action (e.g. a click or hover).

To set up an interactive response, we need to tell Javascript to ‘listen’ for a specific user action or ‘event’. For this, we set up an event listener in Javascript that ‘listens’ for a user interaction with a web page element.

In this case, let’s add an event listener to the selected button element that we have saved within the variable button:

var text = document.getElementById("textToEdit");
var button = document.getElementById("buttonToClick");

button.addEventListener("click", doAThing);

Here, we tell Javascript to listen for an event for button by applying the .addEventListener() method. Next, inside the parentheses, we must include two argument in the following order.

First, we tell Javascript what type of event to listen out for. Here, we specify “click”, but this is only one of many available options!

Following this, we tell Javascript what to do when the event — in this case, a click on the button element — occurs.

For calling on an action to occur in Javascript, we have a useful tool at our disposal: functions. The second argument inside the parantheses, doAThing, makes a call to run a doAThing function. But this doesn’t yet exist!

Let’s write it now.

Writing and executing a function

The syntax of a function in Javascript is as follows:

function doAThing() {
   // Here we write what is to be done when the function is called
}

To create a function, we start by writing the word function followed by whatever we want to call our function with accompanying parentheses. In our case, we call the function doAThing in our event listener so we call our function this so that it is now called when the event listener is activated by a user click. In general, function names should make substantive sense in relation to the action they are executing.

We then open curly braces and write whatever it is we want to happen when the function is called inside these.

Here are some examples of DOM manipulation in response to a click of the button:

DOM Manipulation

Trigger a confirm box

In real-world settings, it is often useful to double-check with a user whether they wish to proceed with an operation. For example, with a purchase or a permanent delete operation, such as clearing a cart.

For this, we can call this confirm method. This opens a confirm box in a user’s browser with the options OK and cancel. Inside the method, we write the text that will precede these two options. For example:

function doAThing() {
    confirm("Are you sure you want to proceed? This operation cannot be undone.");
}

Add these lines of code to your script.js file and save it (your code should now look like below).

Now open or refresh index.html and click the button. This will trigger a confirm alert when the button is clicked. For the first time our page is now responsive to user actions!

Changing the text inside an element

We can fully edit the contents of elements on our page with Javascript. As a simple example, let’s overwrite the text element with a new message when the button is clicked.

function doAThing() {
    text.textContent = "Thank you for []! (e.g. submitting a form)"
}

Applying the method .textContent to an element will change any text inside it to whatever is specified in quotations after the equals sign.

In our case, let’s thank the user for clicking the button. Saving script.js and refreshing index.html, the text on the page is now modified in response to a user clicking the button.

Removing an element

There is less use-value in our example for removing the text element. However, in real-world settings, this is often very useful. For example, removing a product from a shopping basket.

To remove an element, we can apply the .remove() method to the element:

function doAThing() {
    text.remove()
}

Clicking the button now entirely removes the element from our page!

Adding elements

Often, we want to add entirely new content to a page. For example, providing the user with more information about a product when a button is clicked.

We create a new element using the following syntax:

document.createElement('p')

Here we apply the .createElement method to the document object (without specifying where to place it). Inside the parentheses we then specify the type of HTML element we wish to create by its tag name. In the example, we create a new paragraph, so we enter ‘p’.

This is just an example. We can creating any type of valid HTML element this way!

As we want to save this to add some content to this new element in later lines, let’s save this in a variable named paragraph:

var paragraph = document.createElement('p')

Now this paragraph element is available for us to add content by applying the .textContent method, as per previous examples. We also add an ID to the element so it can be selected in further operations using the id method.

var paragraph = document.createElement('p');
    var paragraph = document.createElement('p');
    paragraph.id = "newPara"
    
paragraph.textContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

This is just an example paragraph that could in a real-world setting present the user with more information about a product or service.

If you now save the Javascript file and refresh index.html, you will find that the text still does not appear on the page. This is because we have to specifiy where Javascript should insert it.

We can do this by accessing the body of the body document with document.body followed by the append method to add it to the already-existing elements on the page. The new element will appear as the last element on the page:

document.body.append(paragraph)

Now, for this process to be run when a user clicks the button, all this must be wrapped inside the doAThing function, which is called by our event listener.

function doAThing() {
    var paragraph = document.createElement('p');
    paragraph.id = "newPara"
    paragraph.textContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    document.body.append(paragraph)
}

You now have a formula to create a new element on a web page in response to a user-generated action!

But click the button again. You will notice that it appends another paragraph. And this keeps happening again and again so you have many unwanted duplicates of the paragraph.

This is a common scenario. Let’s solve it by introducing a conditional if/else statement to our function.

If/else for conditional functionality

Sometimes, as per the ongoing example, we want to only execute an action if something is true. In this case, we want to append the text if it doesn’t exist already. And otherwise (i.e. else) we do not want to append (more of the same) text.

For this, we use the following syntax:

if () {
// What to do if the statement in parentheses is correct (not yet specified)
}
else {
// What to do otherwise
}

Let’s modify this to our use example:

if (document.getElementById('newPara') === null) {
    var paragraph = document.createElement('p');
    paragraph.id = "newPara"
    paragraph.textContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    document.body.append(paragraph)
}
    else {
        alert("Error: Text already exists")
    }

In the if statement parentheses, we try to select the new paragraph element by its ID newPara. If it does not exist, the result of selecting this element will be null. This make the statement true and the action following the if curly brace is executed: the text is append.

If selecting the element does not return null we want to do nothing. Just to check the else statement is working, we ask Javascript to initiate an error alert.

If we want this to execute in response to our event listener, we still need to wrap all of this inside the doAThing function:

function doAThing() {
        if (document.getElementById('newPara') === null) {
            var paragraph = document.createElement('p');
            paragraph.id = "newPara"
            paragraph.textContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
            document.body.append(paragraph)
        }
        else {
            alert("Error: Text already exists")
        }
    }

Save your Javascript file and reload index.html. You will find that we have now solved the problem!

In practice this is very useful as there are many situations where what we want to happen depends upon whether something exists or has happened. For example, we may want to display a thank you message to a user for submitting a form if all fields are complete. Otherwise, we could alert the user to the fact that more information is needed.

Utilising a loop

Let’s say that instead of returning this hardcoded text when our event listener is activated, we instead return a list of options for the user to select from. This is a very common operation. For example, we may want to return a list of all current promotions to the user.

Let’s look at the syntax of a loop that can help us with such tasks:

var i;
for (i = 0; i < list.length; i++) {
  // What the loop should do
}

Let’s break this down. First we initialize a variable called i. This is an arbitrary choice – it could be called anything. But calling a looping variable i is convention so let’s stick with that.

Next we write for. This tells Javascript we are about to write a for loop. Following this, we specify the values of the looping variable we just initialized, separated by semi-colons.

First, we specify the starting value of the looping variable. This is commonly 0 as we want to start at the beginning of a list and Javascript counts the first item in a list as 0. But we could start somewhere else in the list.

Next, we specify at what value of the looping variable the loop should stop. This is usually the length of a list and can be accessed easily by applying the .length method to the variable containing the list.

Finally we specify what should happen to the looping variable every time the loop is completed. It is very common to want to increase the value of the looping variable by one so the action in the curly braces applies to all items in the list. The notation for this in Javascript is i++. But we could also specify that something else should happen. For example, i+3.

In our ongoing example, we want to loop through a list of promotions.

In our Javascript file, we first create the current promotions in a variable called promotions. We then write the content of the loop. So this executes in response to a click on our button, we wrap all of this inside the doAThing function:

function doAThing() {

    var promotions = ["Offer 1", "Offer 2", "Offer 3", "Offer 4"]

    var i;
    for (i = 0; i < promotions.length; i++) {
        var promotionToAppend = promotions[i]; // Get promotion in position i
        var container = document.createElement('div'); // Create a new div

        container.textContent = promotionToAppend; // Set text content of new div to content of promotion i
        document.body.append(container) // Append new div to body of the page
    }
}

Now, clicking the button executes the loop. This prints each element in the array of offers to the page.

In the example, we have hardcoded the promotions variable ourselves. But in practice, the list we access is very often external to the Javascript file. For example, a list of promotions would likely be stored in a backend database and retrieved by making a GET request to the server. And can sometimes be very long: for example, we may wish to print a list of countries on a page.

Looping helps us print a list so we don’t have to hardcode it every time. And if the list of the length changes, this is taken into account in the loop. So we don’t have to hardcore that either.

Conclusion

This has been something of a crash course in using Javascript. If you have made it this far, congratulations! You are now familiar with the core concepts needed to program effectively in Javascript!

We hope you found this tutorial useful. Let us know your thoughts in the comments below!

Leave a Reply

Your email address will not be published. Required fields are marked *