Friday, March 02, 2012

JavaScript Basics


JavaScript Logo

This week's post is about the basics of JavaScript.

In part 1, the scripting language is introduced and lightly discussed.

In part 2, the week's class exercise is tackled. The class was given a very barebones Loan Calculator. The user is required to enter some data into a form (amount, interest rate, and payment period), and the loan is calculated.

Part 1: About JavaScript

To skip straight to part 2, click here.

JavaScript is a scripting language that debuted in 1995. It allows for some dynamic content in the normally very static HTML.

JavaScript can be used to modify an HTML document on-the-fly on the client side. This can be used in place of a typical server request, which is much slower.

The "runtime environment" of JavaScript is in the browser. Since it is a scripting language, the browser interprets JavaScript line-by-line. Unlike some other languages, JavaScript is not compiled. The same source code will work on all browsers that support JavaScript, without the need to compile for different platforms.

While the syntax is C-based, and looks similar to programs like Java, it is not object-oriented. JavaScript is said to be object-based. In reality, JavaScript can be adapted to fit most common programming paradigms (functional, imperative, or object-oriented).

Loose Type Definitions

JavaScript is weakly typed, meaning that type definitions are not enforced. One minute a variable can be a String, the next, an integer. It all depends on the context that the variable is being used.

Where to put JavaScript

You can place JavaScript essentially anywhere in a page, simply using the <script> tag.


JavaScript's syntax is exceedingly simple and is based on the C programming language. Therefore, anyone with any experience in a C-based language (C++, C#, Java, among others) can quickly get started in JavaScript. Below is a typical function in JavaScript:

function checkAge() {
    var age = parseInt(prompt("Enter age"), 15);
    if (age < 21) {
 alert("Sorry too young");

Part 2: Exercise

The class was handed a barebones HTML document. The page contained some basic HTML, CSS, and JavaScript. It is a simple loan calculator. The page consisted of a form with three text areas, and a results section. The user was required to enter the amount, interest rate, and the duration of the payment in years.

The class was tasked with making some modifications to the document. The original HTML document can be found at this Pastebin, which is taken from this source.


This is the list of modifications that had to be made to the original document.

  1. Modify the HTML and CSS to make it more presentable.
  2. Show total number of payments.
  3. Display Loan End Date (assuming it starts at the current date).
  4. Add a checkbox showing "Eligible for discount", which reduces the interest rate by 10%.
  5. Add another custom feature.

1. Modify HTML and CSS

The embedded CSS was modified extensively, going from two lines to around 40. The HTML was lightly modified. Some class definitions were added to enable the content to be styled more separately. This is default CSS.

.result { font-weight: bold; }
#payment { text-decoration: underline; }

Below is a screenshot of the HTML document as it originally appeared.

Original Barebones HTML file (click to zoom).

The list of edits is made to the CSS and HTML is below:

  • Increased base font size, and changed the font-family to something sans-serif (e.g. Arial).
  • The table was made larger, with bigger line-heights.
  • The two sections were split into green and yellow backgrounds. A hover effect was added to table rows (see screenshot - a grey background).
  • Headers were made larger, centred, and with a light grey background.
  • The "Compute" button's text was changed to a dark red for contrast.

Below is a screenshot showing the changes.

The HTML file after edits to the style (click to zoom).

2. Showing Total Number of Payments

The total number of payments is the amount of years multiplied by 12, as the payments are monthly. Such that a 5-year loan will have 60 payments in total.

The amount of payments was achieved using the line:

var payments = document.loandata.years.value * 12;

This was displayed to the user next to the monthly payments.

Calculating the amount of monthly payments and showing it to the user.

3. Display the Loan End Date

Assuming the loan started from the current date (i.e. today), then it is trivial to calculate the end date. The following lines of code calculate the end date of the loan.

today = new Date();
yearDue = parseInt(today.getFullYear());
yearDue += parseInt(document.loandata.years.value);

The date the loan is due is displayed next to the total payment amount.

total.innerHTML = (monthly * payments).toFixed(2) + "<br/> due by "+ today.getDay() + "/" + today.getMonth() + "/" + yearDue;
The loan end date is displayed under the total amount.

4. Add Discount Checkbox

The following HTML code was added to the form, adding a simple checkbox.

    <td>Eligible for 10% discount on interest?</td>
     <input type="checkbox" name="discount" onChange="calculate()">

The logic required for the discount is simple: if the "discount" checkbox is selected, then deduct 10 per cent from the interest rate. However, if the discounted rate is zero or a negative number, then place it at 0.001%.

if ( {
    calculatedInterest -= 10;
    if (calculatedInterest < 0) {
  calculatedInterest = 0.001;

The calculated interest rate is then displayed to the user next to the interest payment.

Adding a 10% discount on interest.

5. Adding a Custom Feature

Finally, the class was asked to add a custom feature to the program.

I decided to add an additional checkbox, giving the customer the option to pay via direct debit from a third-party bank account that they own. It's convenient, but if that option is chosen, the interest rate is increased by 0.25%.

The following line of code was added:

if (document.loandata.externalAccount.checked) {
 calculatedInterest += 0.25;

Customers pay for convenience at this fictional bank.


This article hopefully provided you, dear reader, with a quick primer on getting started with JavaScript. As you can see, anyone with experience programming in a C-based language will feel right at home with the syntax, and can immediately enjoy the simplicity of this language.

Live View

You can view my final HTML, CSS, and JavaScript solution here, or by clicking the button below.

Download Source Code

I've made the source code available at this Pastebin, where you can easily view and download my source code.

It's also embedded below.

No comments:

Post a Comment