Anjan Dutta

Function in Javascript a Complete Guide

Function in Javascript a Complete Guide

Updated On: 20/03/2022

A function in javascript is a first-class object which can have both properties and methods. Very easy to write and the syntax matches many of the other programming language.

What is a function

It is a way of writing a set of logic separately from the rest of the code. Functional coding is a clean, readable and reusable approach of programming.

It is also assigned a name for the ease of accessibility. Can we write functions without names? The answer is yes. We call those anonymous functions. I have discussed it later in this article.

Declaration of a function in Javascript

function name(parameter1, parameter2 ....) {
statement1
statement2
.......
}

How to write a function in Javascript

A function declaration has three parts:

  • Name
  • Parameters
  • Statements

Name

A function is given a name so that we can identify it easily. Naming reduces ambiguity among multiple functions. A name gives us a quick idea about what the function does.

It saves a lot of time since we don’t need to read the whole logic again and again before using it.

Function names are case sensitive. fooBar and Foobar will call different functions. Make sure to name it in the most descriptive ways possible.

Some of the naming examples are below.

sendErrorMessage();
send_error_message();
senderrormessage();

The function name is optional. We decide to name a function, depending upon its use. I have described it in more detail in a later section.

Parameters

Sometimes the inner statements of a function may require some external input value.

For example, I am writing a function Add, that will return me the addition of two numbers. Now, there must be some way of passing these two numbers into the function.

Using parameters we do that.

function Add(firstNumber, secondNumber) {
return firstNumber + secondNumber;
}
Add(212, 314);
// 526
Add("Hi", "There");
//HiThere

Yes, the second function call will return a concatenated string if we don’t put a number check for those passed parameters. The plus operator concatenates strings. It’s a feature of javascript.

A function can accept parameters depending on its declaration. There are provisions of handling the case when we don’t pass the sufficient number of parameters in a function call.

We know it as the default parameter. I have written a complete article related to the default parameter.

Parameters can be of any types available in javascript. String, number, array, object and we can even pass a whole function as a parameter of another function.

Statements

Statements are the logic that runs inside the function. It can be a member declaration, business rules, return statement etc.

Scope of a function in javascript

A function has access to its variables, own methods, global variables, global methods, variables and methods declared in its parent function etc.

Sibling functions don’t have access to the scope of each other. A parent function can’t access the scope of its child function.

var globalA = 2;
function parent() {
var parentA = 3;
function child() {
var childA = 5;
console.log(globalA ); //2
console.log(parentA ); // 5
}
function secondChild() {
console.log(parentA ); // 5
console.log(childA ); // undefined
}
}

Types of the function definition

There are many ways of writing a function in Javascript. I have tried to explain them here.

Regular syntax of a named function

function myFunction() {
/*----Your code goes here----*/
}

This example is similar to the first example of this article. Please read that section if it is not clear.

A regular syntax with return value

function myFunction() {
/*----Your code goes here----*/
return "anything";
}

A function can return a value belonging to any of the data types available in javascript.

We can write multiple return statements within a function.

function myFunction() {
if ( /*----Condition----*/) {
/*----Your code goes here----*/
return "something";
}
/*----Your code goes here----*/
return "anything";
}

It is not a good practice or even considered as code blocker if we write multiple return statements within the same block of code.

function myFunction() {
/*----Your code goes here----*/
return "something";
/*----Your code goes here----*/
return "anything";
}

Always make sure to check for this above scenario.

Parameterized function in javascript

A function which accepts one or more parameters is a parameterized function.

We can define a parameterized function like below.

function myFunction(param1, param2) {
/*----Your code goes here----*/
}

There might be scenarios when we can pass only one of the required parameters.

And, we don’t want the function to break our code. Instead, what we want is, to assign certain value by default to the parameters in case if we don’t pass one. This feature is called the default parameter.

Here is an example.

function myFunction(param1 = 10, param2 = 20) {
/*----Your code goes here----*/
}

If we call the above function without passing any parameter like this: myFunction(), the values 10 and 20 will be assigned to param1 and param2 respectively.

There is no defined limit of how many parameters a function can accept. It differs from browser to browser.

But, along with the increase in the number of parameters, a function becomes more complicated to call. And, the functional logic gets more complicated.

function can accept any number of parameters. For a clean logic, we restrict ourselves from passing more than the defined number of parameters. But we can pass any number (not literally, there are browser-specific numbers ) of parameters in a function.

You might ask, what is the point if there is no one to one parametre mapping? How will I access the extra parameters?

Valid question.

Functions have an object called arguments. This is an array object, which stores all the passed parameters in any function.

For example:

function a() {
console.log(arguments);
}
a(1,2,3,4,5);
// Arguments(5) [1, 2, 3, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ]

Immediately Invoked Function Expression (IIFE)

IIFE is the way of immediately calling a function, right after its definition. It saves us time and, we don’t need to keep track of the function call separately.

Like other functions, an IIFE can accept parameters and can return values.

(function myFunction() {
/*----Your code goes here----*/
})();

Anonymous function

These functions have no name and, we use these functions as either IIFE or to pass as a parameter in other functions. Anonymous functions

(function() {
/*----Your code goes here----*/
})();

Recursion in anonymous function is a bit tricky. Since it doesn’t have a name, so we can use a different approach for recursion in anonymous functions. See the below example:

var myFunction = function (val) {
if(val>0) {
console.log('Hello');
arguments.callee(--val);
}
};
myFunction(10);

I have discussed arguments.callee in a later chapter.

Assigning a function to a variable

We can assign any function to a variable and that variable becomes a function itself.

For example, see the below code:

var myFunction = function exampleFunction() {
/*----Your code goes here----*/
}

Here we can call the defined function as myFunction(). It will throw a reference error if we try calling exampleFunction().

Arrow function or fat arrow function

This is a shorter way of writing functions. Because of this '=>' notation, this function is called an arrow or fat arrow function.

These functions do not have any binding of 'this' reference. So 'this' points to the global reference.

To be more specific, this inside an arrow function refers to the window or document object in which the function is defined.

(()=>;{
/*----Your code goes here----*/
})();

High order function

A function that takes another function as a parameter is called a high order function.

See the below example:

function sayHello(callFunction) {
callFunction();
}
function print() {
console.log('Hello');
}
sayHello(print);

It is important to pass a function reference rather than a function call like this sayHello(print()).

If we do this, then the result of the function call gets passed rather than the function itself. So, always be careful while passing a function reference.

It is a very common mistake we make.

Pure function

A pure function returns the same output for the same set of input every time. The result doesn’t depend upon any changeable input from outside.

Below is the example of a pure function:

function incrementByTwo(item) {
return item + 2;
}

Here is the example of an impure function.

function incrementByRandom(item) {
return item + (Math.random() * 10);
}

The return value depends upon a random number. So the output is not predictable even if when input stays the same.

Recursive functions

A recursive function calls itself from within its definition.

function sayHello( number) {
if (number>0) {
console.log("Hello"+ number);
sayHello(--number);
}
}

Always make sure to define an exit criteria in a recursive function. Otherwise, will end up becoming an infinite execution loop.

In above example if (number>0) is the exit criteria.

Predefined function in Javascript

Until now we were talking about custom functions but, there is a huge list of predefined functions in javascript. We can group predefined functions as per data types. There are string functions, numeric functions, array or object functions, date-time functions etc.

In my next article, I will discuss more of these custom functions.