What is a Function?
A function is nothing more than a series of statements which are grouped together to perform a specific task. If there is a task that needs to be performed numerous times inside of a program it is better to define a function for that task. Another way to think of a function is to think of a code block. Inside this code block we have a series of steps to perform which in turn help us complete a task.
Why do we use functions?
By writing and using functions in our main program, we are simply breaking down a large program into smaller pieces with each piece representing a certain task. The beauty of this is each time we need to keep repeating certain tasks in our main program, we simply refer to/call/use the respective function to perform the desired task. Using functions also rids us of having to repeat lines of code over and over again.
What are the main types of functions used in JavaScript?
Functions in JavaScript can be either predefined or user-defined (custom). Predefined functions are those which are already available for use in JavaScript such as the alert() function. This function takes as its argument, a message and then displays it on your screen as an alert box. Many predefined functions in JavaScript are used for converting and comparing data. These functions are also considered ‘Top-Level’ functions as they are widely used when writing all types of JS scripts:
escape(string) – Encodes a string from ASCII into an ISO Latin-1 (ISO 8859-1) character set for HTML processing. It is passed the string to be encoded, and returns the encoded string.
unescape – Converts an ISO8859-1 character set to ASCII.
eval()– Converts a string to integer or float value.
isNaN(value) – If the value passed is a not a number, the boolean value of true is returned, if it is a number, it returns false.
parseFloat() – Returns floating point numbers the same as the parseInt function, but looks for floating point qualified strings and returns their value as a float.
parseInt()– Converts a string to an integer returning the first integer encountered which is contained in the string. If no integer value are found such as in the string “abcd”, then a value of 0 is returned.
typeof operator – This operator returns the type of the object it operates on. Values returned are string values and may be one of “undefined”, “object”, “function”, “number”, “Boolean”, or “string”.
As for now, if you are new to programming and JavaScript don’t worry too much about what all of these functions above do. As you learn more about JavaScript you will eventually start using these on a regular basis when when writing your own scripts or building larger programs of your own.
How to create your own functions in JavaScript
In JavaScript there are many ways to define and use functions. To start off with, I’ll show you one of the simplest ways to create them. In JavaScript and often in programming in general, when we create a function we say that we are ‘defining’ a function or ‘declaring’ a function and as its own entity, it is often referred to as a ‘function definition’. Below is an example of the anatomy of a function definition:
All functions need to be defined/declared in JavaScript. The above function is defined with the function keyword followed by the name of the function, followed by parentheses (). Finally, any code belonging to this function will be executed inside the curly brackets {} where the comment on line 2 is shown.
Below is a simple function definition called ‘sayHello’:
This function is named sayHello and all of its code is inside the curly brackets {}. The first line of this code defines a variable named greeting which houses the string value ‘Hello!’. This value is then shown on the screen to the user using the window object’s alert() method.
You may have attempted to execute the above code only to find nothing happens. The reason nothing happens is because we have to ‘invoke’ or ‘call’ our function. To invoke a function in JavaScript we simply type the functions name followed by parentheses.
Defining and Calling Functions that use Parameters & Arguments
In our earlier example, we created a function named sayHello() which simply outputs the value of a variable onto the screen using an alert box. Sometimes functions perform calculations or operations on bits of information provided to it from outside. When you have a function that requires information in order to perform its task, you need to define a function with parameters.
Parameters are variables and almost always have descriptive names that allow developers and programmers to understand intimately what the named function does. They are bits of information being ‘sent’ to the function when its ‘called’. Think of parameters as ‘placeholders’ for incoming information, and when the function receives this incoming information it will do what its defined to do with it inside its curly brackets (where the functions code resides).
When we define or declare a function with parameters, their order matters. Keep this in mind for later when we go through a more complex example. For now though, take a look at the function definition below:
Here we have defined a function named greetUser and inside its parenthesis we have added a parameter named username. Next we open the curly braces (brackets) {} and begin typing our code. Line 2 of the function code defines a variable named greeting but uses concatenation to create a message using ‘Hello ‘ and whatever username value is followed by an exclamation mark. Finally, we use console.log(greeting) to output the complete message.
Invoking the Function and passing in a single argument
Bits of information are sent to functions via function calls. Usually these are the values which are known as arguments. These are the real bits of information our function will need in order to complete its task. This is achieved on Line 6 when we pass in ‘Manoj’ as an argument to the function call. Normally if a function does not have parameters then you just call invoke it like this:
functionName();
However if it has a parameter then you must place a value in the parenthesis like this:
functionName(argumentValue);
In our example, functionName = greetUser() and argumentValue = “Manoj” so therefore our function call on line 6 is greetUser(“Manoj”). This is how you essentially call or invoke a function that uses parameters/arguments in JavaScript.
Passing two or more arguments in a function call
The below function simply calculates area of a room. If basic math hasn’t escaped your memory, you’ll know that area is equal to the width multiplied by height. The function definition has two parameters: one named width the other height. When we call/invoke this function we pass in two bits of information, one is the value for the width and the other is the value for the height. As I had mentioned earlier, the order in which you name your parameters will determine the order in which you will pass in your arguments in the function call:
The first piece of information the getArea function looks for is a value for its first named parameter, width. The second piece of information it looks for is a value for its second named parameter, height. These two pieces of information will come as arguments supplied to a function call. Once the function receives these two pieces of information, it can go ahead and execute the rest of its code inside its curly braces {}. The above snippet of code if run in your web console will log the following result:
Calling a function inside of function definition
So far we have been defining a function and then simply invoking it. When your programs begin to get large, you will find yourself using certain functions quite frequently. This is good because it means your code is leaning towards DRY approach. DRY in software engineering and programming stands for ‘Do Not Repeat Yourself’. Sometimes we even write simple ‘helper’ functions to deal with small but highly repetitive tasks which in turn can get called from inside other functions. An example of this case is shown below:
Summary
I hope you’ve enjoyed part one of this series. In Part two we’ll look at a few more examples where we define and call functions using parameters and arguments before delving into Anonymous functions and function expressions. You will also be shown another useful way to invoke functions called Immediately Invoked Function Expressions (IIFE).
So to recap this section, here are some important learning points to take away:
- Functions are like mini programs that contain a group of statements to achieve a task inside a larger program
- We use the function keyword to define a function followed by a name for that function
- When we are defining functions we use parameters inside the paranthesis
- When invoking (calling) a function we supply it arguments in the paranthesis
- The order of the parameters/arguments matter
Dušan Milenković says
The way you explained the difference between arguments and parameters proves to me that you’re one of a rare breed in todays saturated dev world, you clearly know what you’re talking about. Sir, going by your explanations alone verifies to me you’re a real programmer. Definetely one of the best articles I’ve come across and wow it was by complete fluke too.
Manoj Kumar says
Thanks Dusan, I appreciate your kind words. The whole idea behind setting up this website was to give back to the dev community and aid others on their quest to becoming professional developers and programmers alike. I felt it was an obligation as a seasoned web developer and veteran Programmer to give back to the community. If you have any questions be sure to drop me an email/fill out my contact form Sir.
Kind Regards,
Manoj