Getting familiar with JavaScript function.

Posted in by Nazrul Islam . Filed in JavaScript

Welcome back to our JavaScript tutorial series. In this tutorial we’ll learn JavaScript function and build a shopping calculator with gathered knowledge we achieved so far. What is function actually? Well – its do things or tasks. Functions considered as heart of any programming language and JavaScript isn’t out of them. Does functions sounds unfamiliar to you? Wait a second! since from our first tutorial, we already used some functions ( alert(); or console.log(); ) to display output result in Alert Box or in Console window. These are built in functions included in language core for providing common solution, Through we go more forward we’ll cover a lot of built-in functions.

Custom JavaScript function:

We’ve discussed only about built-in functions role, but its not enough to solve every problem. We’ll need to make our own function to meet custom requirements. In this parse we’ll talk about custom function’s role and their structure. Suppose we have two number to calculate sum and display output result, and those two numbers are stored in tom and jerry variable. Yes we can do with manually without using any function like this.

This code will generate 50 as output  in console. But if we have a lot of numbers  like this for performing sum, it will become a great headache. We can make a function and do this task easily.

We create a function with function keyword ( its a reserved keyword) next a unique name doSum that identify the function name for executing function later.  After the function name a pair of parenthesis () placed within two variable named num1 and num2 as parameter.  These parameter operates as temporary variable according to which arguments are passes during function execution.  For example we call it as doSum(100, 50); in our first operation. In this case num1 will operates as 100 and num2 as 50. A function can receive multiple parameter by separating them using ( , ) comma.   One thing need to mention that parameters are optional, not every function requires parameter. If your function doesn’t need any parameter, just leave parenthesis pair blank. After parenthesis function body start with a opening curly braces { , and after performing tasks finally function body closed with a closing curly braces }. So we got a function structure like this.

All data inside a function works internally and doesn’t have any affect on outside function until we specify return. In our case we return a local output variable to where function take execution. You may have a question- what is local variable? Well, when we declared a variable inside a function, it is only assessable inside that function. We can’t access it from globally or any other functions. On the other hand global variable  is assessable from any place. But if you manipulate a global variable inside a function, it won’t change the value of global variable if return doesn’t take place.

Function also could be written without any name, these type of functions known as anonymous function. Anonymous function executed immediately  after it reaches ending curly braces. Format shown below.

A starting parenthesis placed before the  function keyword and when function body reaches end with ending curly braces }, we put an empty parenthesis pair () for execution and one additional closing parenthesis ) following a semicolon ; for closing the first parenthesis.

Building a Shopping Calculator:

Write down a form markup like this one.

Shopping Calculator

In this form we’ve set some predefined value as default. Our main target is calculate the total value based upon its another field. A series of operation required to get the total value. First we have to multiply price and unit. Then add tax rate and finally deduction from discount.

We need a way to get every form field value and store in a variable. Our every form field has an unique ID, So we can grab it’s value by document.getElementById(‘quantity’).value.

document.getElementById  is a common JavaScript function to grab a specific DOM element by its ID name. DOM stands for Document object model – consider this as a representation to HTML. We need only field value not the HTML so a .value property do this task placing after document.getElementById. Lets have a look on complete code.

First we grab our form by its ID name and when form is submitted we execute a function. This parse is done with var form = document.getElementById(‘shopForm’);   form.onsubmit = function(){ } .onsubmit is an event listener for form submission. If the form submitted the function which has assigned to it will execute immediately. This is another type of anonymous function, these types of function assigned to specific event listener and when that event occurred function go for execution.

In the event function we grab all our field value except total field and store it on variable like we mentioned earlier. An empty variable  var total; declared to store calculated data for output. We multiply quantity and price and store in total variable then convert tax to decimal  format by dividing 100 and sum it with 1, finally multiply this value with total again. Now this value only need sub from discount and done by total -= discount; At this point total variable contains final calculated data and we are ready to display user the value.  document.getElementById(‘total’).value = total; set the total field value and return false;  prevents the form actually being submitted (to the page named by the form’s action attribute). That’s all for this lesson, hope you enjoyed this lesson.