Understanding Javascript Functions in Depth
14
Jun

Understanding Javascript Functions in Depth

Functions in JS are first-class objects or also known as first-class citizens.
A First-Class Citizen in a programming language is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. In Javascript, Functions are just like objects. The only difference is functions are invocable but objects are not

Example:

OBJECT FUNCTION
Assigns to a variable var object1 = {}; var foo = function() {};
Adds to an array arrayOfObjects.push({}); arrayOfObjects.push(function(){});
Assigns as a property of another object object1.data = {}; foo.data = function(){};
A newly created object/ function
passed as an argument to a function
function enable(object1){
object1.isActive = false;
}
enable({});
function call(foo){
foo();
}
call(function(){});
Returns a new object/ function
from a function
function returnObject() {
return {};
}
function returnFoo() {
return function(){};
}
*Creates a new property
on an object/function
 
var object1 = {};
object1.name = “MainObject”;
var foo = function(){};
foo.name = “Main Function”;

Callback Functions:

A callback function (B) is a function that is passed as a parameter to another function (A).

And the function (A) calls the parameterized function (B) at some particular state of its execution.

Now two questions are here,

Question 1: Why pass a function as a parameter, if we can just call the function B from inside another function A.

Answer 1: Because many times both the functions are not written at the same time, from the same developer, for example, setTimeout() function is already there in the javascript but the callback function we pass into it varies for every problem. But we don’t just go every time and change the internal structure of the setTimeout function.

Another example is the sort() function, we can pass a callback to it in order to tell how to sort an array of objects etc (which key to use to order the objects in the array).

Question:2  If the parameterized Function (B) is to be called at the end of the function (A) then why not call function B right after the calling of function (A), instead of passing function B as a parameter.

Answer2: Okay you sound logical, but what if the function A is an asynchronous function and also will be used to perform various tasks in different scenarios upon completing its execution. In this case, you will need to pass the callback function because of two reasons,

  1. You do not know prior to defining the function (A) that what the function (A)’s the user wants to run on completing its execution so function (B) would not be the same every time. (dynamically changing the after effect of function A.)
  2. You cannot call function (B) right after function (A)’s calling because function (A) is async.

Functions as Objects

In javascript, functions can also have properties just like objects.

function palindrome () {}
palindrome.cache = {};

By adding a property to a function, we can preserve the previous output the function generated, and many other things. We can also easily implement memorization by using this.

function palindrome (n) {
    if (!palindrome.cache) {
        palindrome.cache = {};
    }
    if (palindrome.cache[n] !== undefined) {
        return palindrome.cache[n];
    }
    for (let i = 0; i<n.length / 2; i++) {
    // check if first and last string are same
        if (n[i] !== n[n.length - 1 - i]) {
            palindrome.cache[n] = false;
            return false;
        }
    }
    palindrome.cache[n] = true;
    return true;
}
  1. Immediately invoked functional Expressions (IIFE)
(function(app) {
    app.val1 = 11;
})(Const);
var Const = {};

A function definition inside parentheses makes it immediately invokable, and we can invoke them by ().

In the above example, we are passing an argument Const to the function.

And the main purpose of IIFE is modularization.

The main goal of IIFE is to avoid polluting the Global Scope.

Polluting the global namespace can be problematic because there is a chance of overriding variables and functions declared in different files.

And you also have to keep track of every variable declared in the Global Scope.

  1. Arrow Functions: also called ( ‘=>’ Fat arrow Operator)

Arrow functions are just the syntactic sugar from ES6, to make the code shorter and more succinct.

For example: to sort array we wrote

var values = [0, 3, 2, 5, 7, 4, 8, 1];
values.sort(function(value1, value2) {
    return value1 – value2;
});

But using the arrow function we could write it in a much shorter way.

var values = [0, 3, 2, 5, 7, 4, 8, 1];

values.sort((value1,value2) => value1 – value2);

Remember when we use curly braces, we need to use the return statement, else as in above case if we don’t use curly braces then we don’t need and cannot use return statements.

values.sort((value1,value2) => {

return value1 – value2// in this case we need to use a return statement because we are using curly braces.

});

Example 2:

function greet1(name) {
    return "Welcome "+ name;
}
greet1("Ficode");

But using Arrow function we could write it in more succinct manner:

greet2 = name => "Welcome " + name;

greet2("Ficode");

If you want to hire a Javascript developer, Ficode is here to help you so please don’t hesitate to contact us today on info@ficode.com.

share
Meet the Team: Ankita Sharma, Associate Software Engineer (Mobile Applications)

Meet the Team: Ankita Sharma, Associate Software Engineer (Mobile Applications)

previous-blog-arrowPrevious
Meet the Team:  Neha Bharti, Associate Project Coordinator

Meet the Team: Neha Bharti, Associate Project Coordinator

next-blog-arrowNext