Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript Separation of Concerns

In the previous lesson, we mixed HTML and JavaScript together and our program worked just fine. Now imagine an application that has thousands of lines for HTML and hundreds of lines for JavaScript. Mixing them together makes it very difficult to maintain the application.

Let's look at another scenario, let's say you create a page that shows tweets from your twitter account and you mix the HTML and JavaScript. What if you have another page that needs the tweets functionality? Then you will be forced to write the same code again.

To solve the above problems, we can work with the concept of Separation of Concerns. Actually Separation of Concerns is a much broader term that applies to computer science but for simplicity's sake, we will say its the practice of separation the HTML from the JavaScript files. This means we create a JavaScript file then embed it into the standalone HTML file. This makes writing code easy and promotes code reusability.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-soc

Open the directory javascript-soc in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • index.html - this file will be used to for code dealing with the switch statement

The following visualizes our project setup

javascript-soc
-index.html
-app.js

JavaScript Files

The JavaScript files end with the extension .js. Once the browser loads file with .js extension, it will know that it is a JavaScript file and it will take the appropriate action.

In this lesson, we will work with the hello world application and refactor the code to have a separate file for the JavaScript code.

Refactoring Hello World Example

In the previous lesson, we worked with the following code

<!doctype html>
<html lang="en">
    <head>
        <title>JS Hello, world!</title>

        <!-- Bootstrap CSS -->
        <link rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <h2>JavaScript Hello World!</h2>
            <form>
                <div class="form-group">
                  <label onmouseout="eventHandle" for="name">Enter Your Name</label>
                  <input onchange="eventHandle" id="name">
                
                </div>
                <button onclick="sayHello()">Hit Me</button>
              </form>
              <p id="message">Your message will be displayed here</p>
        </div>
        <script>
            function sayHello(){
                var name = document.getElementById('name').value
                document.getElementById('message').innerHTML = 'Hello ' + name;
            }
        </script>
    </body>
</html>

We will now refactor the above code so that we have Separation of Concerns.

Create a new file app.js

Add the following code to it.

function sayHello(){
    var name = document.getElementById('name').value
    document.getElementById('message').innerHTML = 'Hello ' + name;
}

HERE,

  • function sayHello(){...} defines a new function called sayHello
  • var name = document.getElementById('name').value grabs the value of the element with the id value of name.
  • document.getElementById('message').innerHTML = 'Hello ' + name; gets the element with the id value of messages replaces its contents with a greeting message

Note: unlike in the above example, we have skipped the opening and closing script tags. This is because we have saved our file with the .js extension so that is taken care of for us automatically.

Let's now modify the HTML file to include the JavaScript code.

<!doctype html>
<html lang="en">
    <head>
        <title>JS Hello, world!</title>
        <!-- Bootstrap CSS -->
        <link rel="stylesheet"
         href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <h2>JavaScript Hello World!</h2>
            <form>
                <div class="form-group">
                  <label for="name">Enter Your Name</label>
                  <input type="text" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name">
                
                </div>
                <button onclick="sayHello()" type="button" class="btn btn-primary">Say Hello</button>
              </form>
              <p id="message">Your message will be displayed here</p>
        </div>
        <script src="app.js"></script>
    </body>
</html>

HERE,

  • <script src="app.js"></script> the script tag now uses the src attribute to point to our JavaScript file. The rest of the load remains the same

Load the file index.html into your web browser.

You should be able to get the following form

JS Hello World

Enter your name then click on Say Hello button

You should be able to get the following results.

JS Hello World

JavaScript External Files Performance

While it is easy to maintain JavaScript files that have been written in separate files, this comes with a performance cost. Loading a lot of external JavaScript files can slow down your web application. Small JavaScript files that are specific to a single page are better off embedded into the HTML page itself instead of loading it as a separate file.

We will talk more about how to improve performance when working with JavaScript in future lessons.

Summary

It is a best practice to create separate JavaScript files if you have a lot of code inside your JavaScript functions and if you need to reuse the same code. But if you have a relatively small JavaScript code, then you can just inline it within HTML to improve performance. You can use the <script></script> tag to include the external JavaScript file.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript in Browsers

JavaScript in Node

Leave A Reply