Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are these lines doing?

I'm starting learning javascript for a project, I've found a script that does a part of what I need to do, I'd like to know how it works, both for me and in case it needs to be modified.

Originally it was used inside the page, now I've put it in a file on its own and does not work anymore, so I'm dividing it in parts, because I fail to get the whole thing.
Here is what bother me most for now:

1) Is this a declaration of a function? What is its name? How can it be invoked?

(function() {
    //some code
})();

2) No clue of what is going on here

var VARIABLE = VARIABLE || {};

3) Am I defining the implementation of methodCall here? Something like overriding a method in Java?

VARIABLE.methodCall = function(parameter) {
    console.log("parameter was: " + parameter);
};

Thank you in advance for your help.

like image 933
Alberto Zaccagni Avatar asked Dec 12 '22 22:12

Alberto Zaccagni


1 Answers

1) creates an unnamed function and executes it. this is useful for creating a scope for local variables that are invisible outside the function. You don't need to invoke it aside from this, the '()' at the end does that for you.

2) if variable is null/undefined, set it to an empty object.

3) yes, that should work as you expect, you can call VARIABLE.methodCall(parameter)

in response to your comment, here is a common example

function foo (VARIABLE)  {
   var VARIABLE = VARIABLE || {};
}
like image 155
Jimmy Avatar answered Jan 06 '23 04:01

Jimmy