Quick Guide to JavaScript Functions

Quick Guide to JavaScript Functions

We have learned about functions in JavaScript. But in this blog, we will dig deep into the JavaScript function.

You can check out the JavaScript series Here before going through this blog. I have covered required concepts in my previous blogs.

Default Parameters

When we call functions with parameters, we also pass values while calling the function. But if we don't pass the value and the function has parameters it gives an error.

To overcome this we can pass default values to parameters. So when parameters are present and if we don't pass any value while calling the function, then parameters will hold that default value.

Without default values for parameters

function isLogin(userName){
    console.log(userName); 
}
isLogin(); // undefined

With default values for parameters

function isLogin(userName="defualt value"){
    console.log(userName);
}

isLogin(); // will print default value

Higher Order Function

A “higher-order function” is a function that accepts functions as parameters and/or returns a function.

Let's try understanding using an example

Function as Parameter

let toArray = function(str){
  let converted = str.split('');
  return converted;
}

let uppercase = function(str){
  return str.toUpperCase();
}

// Higher Order Function
function HOF(str , fn){
  console.log(fn(str));
}

// Calling Higher Order Function
HOF("Javascript" , toArray); // J,a,v,a,s,c,r,i,p,t
HOF("Javascript" , uppercase); // JAVASCRIPT

Return a function

We are returning function from function. So we have to pass 2 parameters but in different way which we will see in example.

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

// 1st method of calling
let cal = greetings("Hello");
cal("JavaScript");

//2nd method of calling
greetings("Hello")("JavaScript")

Call, Apply and Bind method

All 3 methods do the same thing differently. Let's check them on by one.

Call

Suppose we have 2 cab companies. we make deferent for both cab company.

let ola = {
  name: 'ola',
  tax: '5%',
  book(customerName, currentLocation, destination){
    console.log(`You have Booked ${this.name} cab in the name of ${customerName} from         
    ${currentLocation} to ${destination} with ${tax} tax.`)
}
}

let uber = {
  name:'uber',
  tax: '12%',
}

ola.book("Kedar","Pune","Mumbai");

Now in the above example if I want the same book method in uber. I can't copy and paste every time and it is not good practice to have the same method in every object. So we can use call method.

Syntax of call

methodName.call(obj2, val1,val2......);

Let's try this in above example.

let ola = {
  name: 'ola',
  tax: '5%',
  book(customerName, currentLocation, destination){
    console.log(`You have Booked ${this.name} cab in the name of ${customerName} from         
    ${currentLocation} to ${destination} with ${tax} tax.`)
}
}

let uber = {
  name:'uber',
  tax: '12%',
}

ola.book("Kedar","Pune","Mumbai");

let bookingMethod = ola.book;

bookingMethod .call(uber,"John","Mumbai","Bangalore");

I created a variable that has a method from desired object and user that variable with the call method with an object which don't have that object and then passes parameter values. So now this will refer to uber instead of ola.

apply

It is the same as the call method. But instead of parameters, it takes an array as a parameter.

let ola = {
  name: 'ola',
  tax: '5%',
  book(customerName, currentLocation, destination){
    console.log(`You have Booked ${this.name} cab in the name of ${customerName} from         
    ${currentLocation} to ${destination} with ${tax} tax.`)
}
}

let uber = {
  name:'uber',
  tax: '12%',
}

ola.book("Kedar","Pune","Mumbai");

let bookingMethod = ola.book;
let parameters = ["John","Mumbai","Bangalore"]
bookingMethod.apply(uber,parameters);

bind

The bind() method returns a new function, and when invoked, has this set to a specific value.

The following illustrates the syntax of the bind() method.

fn.bind(thisArg[, arg1[, arg2[,...]]])

let ola = {
  name: 'ola',
  tax: '5%',
  book(customerName, currentLocation, destination){
    console.log(`You have Booked ${this.name} cab in the name of ${customerName} from         
    ${currentLocation} to ${destination} with ${tax} tax.`)
}
}

let uber = {
  name:'uber',
  tax: '12%',
}

const uberKedar = book.bind(uber);
uberKedar("Kedar","Bangalore","Mumbai");

const uberKedar = book.bind(uber,"Kedar");
uberKedar("Bangalore","Mumbai");
uberKedar("Mumbai","Bangalore");

Difference between call(), apply() and bind()

  • call: binds the this value, invokes the function, and allows you to pass a list of arguments.
  • apply: binds the this value, invokes the function, and allows you to pass arguments as an array.
  • bind: binds the this value, returns a new function, and allows you to pass in a list of arguments.

Immediately Invoked Function Expression (IIFE)

A JavaScript immediately invoked function expression is a function defined as an expression and executed immediately after creation. When you define a function, the JavaScript engine adds the function to the global object. IIFE execute only once.

// Normal function
(function (){
  console.log("Will run only once automatically");
})();

// Arrow function
(() => console.log("Will run only once automatically"))();

Notice how the function has no name and it is wrapped in round braces() and with() it is called immediately

Closure

A closure gives function access to all the variables of its parent function, even after that parent function has returned. The function keeps a reference to its outer scope, which preserves the scope chain throughout time.

function count(){
  let passenger = 0;
  return function(){
    passenger++;
    console.log(passenger);
  }
}

let booking = count();
booking(); // 1
booking(); // 2

console.dir(booking); //to see closure in browser console

Hope you understood everything. Follow for more blogs. You can check out the JavaScript series Here

Did you find this article valuable?

Support Kedar Makode by becoming a sponsor. Any amount is appreciated!