Javascript functions explained to stay with you forever

Of all the capabilities, I really like the way function is implemented in Javascript. I often wonder if there is anything that could have been done better.

In this article, I will introduce Javascript functions. In the next few articles, I will build on that and enable you to understand function thoroughly.

Prerequisite

I am assuming that you understand HTML and CSS. Also, you have some familiarity with Javascript. We have always seen people repeating the same code again and again and we feel a need for putting the common code in a single place and reuse them. Functions help us achieve that in different ways with different powers !

To explain different capabilities of functions, I will use different HTML / Javascript combinations. I do have a separate course on Javascript where I help you build applications using Javascript and teach you all the concepts.

Let’s start with an empty javascript file and a basic HTML file(say basic.html), which just gives you an orange play area:

<html lang="en">
<head>
<meta charset="utf-8">
<title>Javascript Basics</title>
<style>
body {
background-color: orange;
}
div#playarea {
position: relative;
width: 900px;
height: 600px;
margin: auto;
}
</style>
</head>
<body>

 



</body>
</html>

Following image shows the output:

3

Let’s Interact

Let’s interact with the browser a bit and see how it feels. For this let’s write following lines of code

document.write("Hello, How are you?");

console.log("Now that I met you, I am feeling great!");

alert("When someone pops-up suddenly, it feels so distracting!");

What you see here is 3-ways of interacting with the page

  1. By updating the page itself: generally your end users will do this
  2. Through console logs: often used in initial development phase for debugging
  3. Through Pop-ups: to confirm something or seek some quick input

In each of these cases, what have you done? Basically, you are calling the write method of the Document Object, log method of the Console Object and alert method of the Window Object. Even though you don’t know or understand Javascript function, you still end up using some of these basic things and in few lines of code, you are able to see the power of Javascript.

What is function?

A function is a block of code, all designed to work together to perform a specific task, that is defined once and may be executed / invoked a number of times. Yes, this helps you reuse your code in a big way.

Defining a function

In its simplest and most explicit form, you define function as shown below:

function calculateDistanceTravelled( startPos, currentPos ) {
    var distance = Math.sqrt( Math.pow(currentPos.xPos - startPos.xPos, 2) + Math.pow(currentPos.yPos - startPos.yPos, 2));
    return Math.ceil(distance);
} 

Here you have done following

  • Used function keyword to explicitly define a function with the name, calculateDistanceTravelled
  • Passed two parameters (javascript objects)
  • Used a local variable inside the function to hold the calculated distance value
  • Applied ceiling on the distance and
  • returned a value from the function to indicate that the function execution ends here and transfers the control back to the caller
    • Note that, if the return statement is not explicitly provided then undefined is returned as a value.

Invoking a function

Now that you have got your function defined, invoking the function is straightforward. All you need to do is pass the desired arguments to the calling function, as shown below by including the below code in our basic.html.

function calculateDistanceTravelled( startPos, currentPos ) {
 var distance = Math.sqrt( Math.pow(currentPos.xPos - startPos.xPos, 2) + Math.pow(currentPos.yPos - startPos.yPos, 2));
 return Math.ceil(distance);
} 
var startPos = { xPos : 20, yPos : 20 };
var currentPos = { xPos : 40, yPos : 40 };
document.write("You have travelled : " + calculateDistanceTravelled(startPos, currentPos) + " KM ");

You shall be able to see an output as shown below:

2

Function as expression

While defining the function, in the example we used the Pow method of the Math object. It would have been nice to use an explicit function like square to calculate square of a number. Let’s do that using a function expression.

var square = function(x) {
return x * x;
};
function calculateDistanceTravelled(startPos, currentPos) {
    var distance = Math.sqrt( square(currentPos.xPos - startPos.xPos) + square(currentPos.yPos - startPos.yPos));
    return Math.ceil(distance);
} 
var startPos = { xPos : 20, yPos : 20 };
var currentPos = { xPos : 40, yPos : 40 };
document.write("You have travelled : " + calculateDistanceTravelled(startPos, currentPos) + " KM ");

What did you exactly do?

  • You just created a function as an expression and assigned it to a variable named square
  • Used this variable as a function inside the calculateDistanceTravelled function definition

Let’s play a bit

  1. Let’s move the function invoking code (i.e. the document.write statement) above the function declaration. What do you think should happen?
  2. Let’s move the actual function call (i.e. the document.write statement) before the square function expression. What do you think should happen?

While the play#1 has no impact on the outcome, after the play#2, you start seeing an error. Following block shows the modified code after play#2:

var startPos = { xPos : 20, yPos : 20 };
var currentPos = { xPos : 40, yPos : 40 };
document.write("You have travelled : " + calculateDistanceTravelled(startPos, currentPos) + " KM");

function calculateDistanceTravelled(startPos, currentPos) {
    var distance = Math.sqrt( square(currentPos.xPos - startPos.xPos) + square(currentPos.yPos - startPos.yPos));
    return Math.ceil(distance);
} 
var square = function(x) {
return x * x;
};

You start seeing the following error, where functionBasics.js is the file in which we are writing all the java script code:

Uncaught TypeError: square is not a function
    at calculateDistanceTravelled (functionBasics.js:8)
    at functionBasics.js:4

Let’s understand this error:

  • The concern is not about the definition of calculateDistanceTravelled
  • The concern is that square function is not defined

Function Declaration Vs Function Expression

You noticed that it whether you use function declaration or function expression, eventually, you have a function, which you can call in your code.

However, there are significant differences among these two approaches. Of course, they are useful in different use cases and hence they do need to exist.

The main difference is the way the browser parses the code.

  1. Before executing any code, browser first looks for function declarations and keep them in one place
  2. Then it executes rest of the code sequentially

The function expression gets executed during second pass. Now let’s look at the error that you observed in previous example.

The following statement invokes calculateDistanceTravelled function, which in turn uses square function:

document.write("You have travelled : " + calculateDistanceTravelled(startPos, currentPos) + " KM");

The square function gets defined as an expression at the later part of the execution and until then it is not known to the browsers. Hence, it says “square is not a function”.

Following table summarize the differences:

Function Declaration Function Expression
Parsing by browser Browsers explicitly look for them in the first run. Browser executes them like any other statement during the second pass (i.e. at the execution time)
Name They have explicit name that they get as part of the standard declaration.

  • The function name is used as a reference to invoke a function call
They don’t have a name as they get assigned to a variable as part of the expression.

  • Using variable name you invoke a function call

Since this variable allows you to invoke a function, basically it points to a function, i.e. the value that it contains is a reference to a function.

Reference Creation When the browser find a function declaration, it creates variable with the same name as function name and assigns the new function to it.

Note that a function declaration doesn’t return a reference.

A function expression returns the reference to a new function created by the expression, which the declared variable refers to.
Statements Function declarations are statements Function expressions are used in a statement
Timing of function creation The function gets created before the rest of the code gets evaluated The function gets created at runtime. If this part of code, doesn’t get invoked due to whatever reasons then such expressions will not even get evaluated and hence the function related expression will not create any function.

Now that you understand the basics of function, let’s talk about different aspects of functions.

Different Aspects of Functions

Parameter and Arguments

We can pass zero or more parameters to the function. Also, while invoking the function, we can provide zero or more arguments.

You may like to take a note of the following:

  • Javascript will go ahead with the execution, even if you will not pass the exact number of arguments
  • It is our responsibility to use the parameters appropriately in the function to drive the appropriate logic flow. Of course, this can be flagged as an error explicitly by handling in the code but Javascript will leave such things to the developer.
  • Each parameter acts like a local variable inside the body of the function
  • If you pass more arguments than expected then the additional arguments will be ignored
  • If you pass less arguments than what is expected then for the remaining arguments an undefined value will be considered
  • There is no type checking in arguments and hence anything can be passed

Parameters get passed as values

Javascript passes arguments using pass-by-value approach. Whenever you pass arguments, the values first get copied and then they get assigned to the corresponding parameters.

Any change in the parameter value will impact only to the parameter and not the variable (from the outer scope), which you may be passing to the function.

Note

I have used the term parameter as well as arguments. When you declare the function, you define the values known as parameters and when you call the function you pass values, which are called arguments.

Global and Local Variable

While the whole Javascript is designed around globals (visible everywhere), we put significant effort in ensuring that things don’t become global. Hence, while working with the functions, it is important to understand the scope of variables, specifically when a variable becomes a global variable.

A variable is a global variable when

  • It is declared in the global scope
  • It is used inside a function without “var” keyword preceding the variable name

A variable declared inside a function using a var keyword is called a local variable.

Following table shows a few important differences between a global and local variable:

Global Variable Local Variable
Lifetime As long as page is open and it is not refreshed Within the execution of the containing function
Access Can be accessed from anywhere in the page Can be accessed only from that function and that too from the point where it was first defined.
Behaviour in nested function Available across all the functions Apart from the same function, the variable is available for only the inner function. The inner function has access to the actual variable and any modification will have an overall impact.
Best Practices
  • Should be declared at the top of the page.
  • Must be avoided as much as possible
  • Should be declared at the top of the function
  • Must ensure that you use “var” keyword

Notes

Unlike the traditional languages like C/Java, Javascript doesn’t provide block scoping. It provides function scope (i.e. local variable declared in one function will not be visible to local variable in other function, except inner functions).

  • Hence, you do need to ensure that you don’t assume block level scoping in JS.
  • Also, you shall declare variables on top of the function as declaring as late as possible is more suitable for languages which supports block scoping

Following diagram depicts how the variables resolves its scope:

Shadowing Parameter or Global Variable

You must be careful while declaring a variables inside the function. In case you declare a variable with the same name as the global variable name or the parameter name then such variable declaration will ignore the global declaration or parameterization and use the value of local variables instead.

For example in below code, the local variable will be used to calculate the distance between two positions:

var startPos = { xPos : 20, yPos : 20 };
var currentPos = { xPos : 40, yPos : 40 };

function calculateDistanceTravelled(startPos, currentPos) {
var startPos = {xPos:10, yPos:10};
    var distance = Math.sqrt( square(currentPos.xPos - startPos.xPos) + square(currentPos.yPos - startPos.yPos));
    return Math.ceil(distance);
} 
var square = function(x) {
return x * x;
};
document.write("You have travelled : " + calculateDistanceTravelled(startPos, currentPos) + " KM");

Always, remember that proximity matters. What it also means that if the local variable is declared at the later stage in the function then until that point the global variable or parameter will be effective.

Note

Try to move the local variable after the call to the square function and see the difference.

Function as Object

What I find amazing in Javascript is that a function is an Object. Coming from any traditional programming background and thinking that a function is an Object, looks like an absurd thought. While Object is a huge topic in itself, here I will cover things which are relevant to a function.

At a very high level, Objects are collections of name/value pairs having a hidden link to a prototype object. The Function objects are linked with Function.prototype, which is linked with Object.prototype. The easiest way to visualize a function as an object is to add state and behaviour to it and then print its properties. The following piece of code adds state and behaviour into the square object, which is a function, and prints the property of this object:

square.defaultNumber = 1;
square.calculateDefaultNumber = function() {
return 1;
}
for (var prop in square) {
console.log(prop + ": " + square[prop]);
}

Now that you understand that a function is an object, you shall find it easier to understand that

  • A function can be returned from a function
  • A function can be passed as an arguments to another function
  • A function can be stored in a variables, another object or in an array
  • A function can have states and methods
  • You can call the function inside its own body and achieve recursion

Interestingly, even with all these capabilities, you can just invoke them as if they are pure play a function. Isn’t that amazing?

Two additional parameters while invoking a function

When you invoke a function, in addition to the declared parameters, two additional parameters get passed automatically:

  • this : this points to the object in which this function is defined. If there is no specific object mentioned then by default the function will be linked with the global object
  • arguments : arguments array contains the arguments passed to the function. This could be pretty useful to implement functions where the number of arguments are not known upfront

You can make use of arguments object to check if you have the required arguments or not and then you can proceed with the execution of the function.

Bonus Notes

Try running following code to see what goes inside the arguments:

var square = function(x) {
console.log(arguments);
return x * x;
};
var squareOfFive = square(5);
document.write("Presenting the Square of Five !!!"+ squareOfFive );

Conclusion

In this article, I have explained the basics of Javascript functions. Also, I introduced you to the different important aspects of the JS function. In the beginning of my own experience with Javascript, I did find functions to be amazing but sometimes overwhelming. Hence, my intention was to make it easier for you to understand and become a great web / mobile application developer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s