JavaScript : Functions at a glance

JavaScript : Functions at a glance

ยท

4 min read

Functions

As we know, functions are nothing but a block of code which executes a particular task and can be reused. However, functions in JavaScript are a tad bit different from functions in the majority of languages.

Default Parameters

Let's consider a function which prints the name and balance of the user. It works fine as long as both parameters are passed by user.

function accBal(user, bal){
 console.log(`Current balance of ${user} : ${bal} !`);
} 

accBal('Tanishka', 80000); // Current balance of Tanishka : 80000 !

Sometimes, a parameter isn't passed by the user. In such cases, an error occurs and the function can't be executed. Therefore, we assign a default value so that function can use if the user has not provided one.

function accBal(user, bal = 0){
 console.log(`Current balance of ${user} : ${bal} !`);
} 

accBal('Tanishka'); // Current balance of Tanishka : 0 !

First Class Functions

Functions are just another type of object in JavaScript. Since objects are values, functions are values too. This is what we call first-class functions.

Due to this, we can store functions in variables, pass functions as arguments to other functions, return functions from other functions and even call methods on functions.

Higher Order Functions

A function that receives a function as an argument or returns a function is called a higher-order function. This is possible because of first-class functions

const greet = () => console.log('Hello !');
btn.addEventListener('click', greet);

In the above example, the event listener is a higher order function and greet is a call-back function. The greet function would be called by the event listener later when the user clicks the button.

const greet = function (greeting) {
    return function(name){
        console.log(`${greeting}, ${name} !`);
    }
}

const res = greet('Hey');
res('John'); // Hey, John !

greet('Hello')('Michael'); // Hello, Michael !

Here, greet function returns another function. That's why the result of call of greet is stored in a variable and then that variable is treated like a function call by passing another argument.

Or we could just pass both arguments simultaneously in two different parentheses.

Call, Apply, Bind Methods

Call

Call is a function that helps you change the context of the invoking function. It helps you replace the value of 'this' inside a function with whatever value you want.

Syntax

func.call(thisObj, args1, args2, ...);

Example

const obj_1 = {
  teacher: "Millie",
  printName: function (myName) {
    console.log(`My name is ${myName}, student of ${teacher}`);
  },
};

const obj_2 = {
  teacher: "Sadie",
};

obj_1.printName("Tanishka"); // My name is Tanishka, student of Millie
obj_1.printName.call(obj_2, "Rose"); // My name is Rose, student of Sadie

In the above example, we called the first function for the second object and the change of this word can be seen with the change in the teacher's name.

Apply

Apply method is just the same as the call method, the difference being - you need to pass arguments in form of arrays.

Syntax

func.apply(thisObj, argumentsArray);

Example

const obj_1 = {
  teacher: "Millie",
  printName: function (myName) {
    console.log(`My name is ${myName}, student of ${teacher}`);
  },
};

const obj_2 = {
  teacher: "Sadie",
};

obj_1.printName("Tanishka"); // My name is Tanishka, student of Millie
obj_1.printName.apply(obj_2, ["Rose"]); // My name is Rose, student of Sadie

As you can see, this is the same example that we took for the call method but we just passed 'Rose' in the array.

Bind

Bind method is somewhat different from call and apply. It returns a new function, that's why we need to store it in a variable first and then pass variables to that variable.

Syntax

const returnedFunc = func.bind(thisObj);
returnedFunc(args1, args2, ...);

Example

const obj_1 = {
  teacher: "Millie",
  printName: function (myName) {
    console.log(`My name is ${myName}, student of ${teacher}`);
  },
};

const obj_2 = {
  teacher: "Sadie",
};

obj_1.printName("Tanishka"); // My name is Tanishka, student of Millie
const retFunc = obj_1.printName.bind(obj_2);
retFunc('Rose'); // My name is Rose, student of Sadie

We stored the newly returned function in a variable name retFunc and passed arguments to it.

Closures

A closure is the combination of a function bundled together with references to its surrounding state. In other words, a closure gives you access to an outer function's scope from an inner function.

JavaScript, closures are created every time a function is created, at function creation time. Let's see an example for a better understanding.

function main() {
  var name = "Jacob"; 
  function disName() {
    console.log(name);
  }
  disName();
}
main();

main() creates a local variable called name and a function called disName(). The disName() function is an inner function that is defined inside main() and is available only within the body of the main() function. Note that the disName() function has no local variables of its own.

However, since inner functions have access to the variables of outer functions, disName() can access the variable name declared in the parent function, main().


Hope you understood everything in this blog. Stay tuned to learn more about arrays in the next blog! ๐Ÿ˜„

ย