0

How to understand the brackets in the last line and how to call the function.

I think it would be fun()(1,1,handle); if there is no (); at last but what's the (); mean?

var handle = function(boolean){
  alert(boolean);
}

var fun = function(){
  // Some definition
  // Some function
  
  return function(a,b,handle) {
    // Some process
    if (a == b) {
      handle(true);
    } else {
      handle(false);
    }
  }
}();
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Menkot
  • 694
  • 1
  • 6
  • 17

1 Answers1

0

Its immediately invoked function expression, you can learn about it here.

It is used cause the function becomes a function expression which is immediately executed. The variable within the expression can not be accessed from outside it.

like this fun immediately executed. for eg:

function greatings() {
  console.log('Welcome to GFG!')
}
// Execution of Regular Function.
greatings();
// IIFE creation and execution.
(function () {
  console.log('Welcome to GFG! in IIFE')
})()

And for your question, the () is to invoke your function and you will call the function as fun(1,1,handle) like:

var handle = function (boolean) {
  console.log('coming here')
}

var fun = (function () {
  // Some definition
  // Some function

  return function (a, b, handle) {
    // Some process
    if (a === b) {
      handle(true)
    } else {
      handle(false)
    }
  }
})()

fun(1, 1, handle)
Ashishssoni
  • 729
  • 4
  • 14