Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript () operator invokes function [duplicate]

Tags:

javascript

I have been using javascript for a while now and am starting to realise how badly I have been using the language. Some more advanced aspects of it are comming to light such as closures, module pattern etc.

Can someone explain how the () operator works when placed at the end of a function i.e. why does it immediately invoke it - i havent seen this before and am puzzled as to how this actually works.

as in:

var myFunct = function() {
    alert("here");        
}();

The () at the end will immediately invoke the function.

like image 893
David Avatar asked Dec 03 '22 04:12

David


2 Answers

A function is an object. Using function_name refers to the actual function object. And function_name() refers to the result of the function. For example:

function foo() {
  return 2;
}

typeof foo()
= "number"

typeof foo
= "function"
like image 115
remi Avatar answered Dec 28 '22 21:12

remi


Javascript functions are first-class objects. They can be stored, passed and returned. Since they're functions, they can also be called.

So you can write this:

var f = function(message) {
    window.alert(message);
}

f("Hello, world!");

That creates an anonymous function object and stores it into f. Then it calls it through f().

You can also create an anonymous function object and call it immediately without storing it in a variable:

(function(message) {
    window.alert(message);
})("Hello, world!");
like image 36
Frédéric Hamidi Avatar answered Dec 28 '22 22:12

Frédéric Hamidi