Complicated way of Javascript function - javascript

I observe a different (different for me) way to write function of javascript or jquery,,,you guys kindly guide me about the working of this one.
(function ()
{
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
}());
Truly I'm not understanding (function(){}());.
No one is calling it but it is being called properly.
If any piece of tutorial you guys know, concerned to it, then tell me.

That is a Immediately-Invoked Function Expression (IIFE). In other words, a function that gets executed when defined

Declaring a function without a name is normally used to assign that function into a variable. A useful trick which allows you to pass the entire function around and call it later.
In this case it's not being assigned to anything, but the extra set of brackets after the braces are effectively calling the function immediately.

Related

Immediately Invoked Function Expression: Where to put the parenthesis?

I've seen IIFE's written:
(function() {
console.log("do cool stuff");
})();
as well as:
(function() {
console.log("do more cool stuff");
}());
They seem to work the same in any context I've used them, though in cases I've been told one way is right and the other is wrong, vice versa. Does anyone have any solid reason or logic as to it being written one order over the other? Is there some cases where there could be potentially more going on after the function body closes but before the invoking parenthesis come into play, or after but before that final closing parenthesis? I've mostly used these in an Angular module closures and can't seem to find anything on any real reason to go one way or the other, wondering if anyone had different experience.
Short answer: It doesn't matter, as long as you put them there.
Long answer: It doesn't matter except in the case of arrow functions, because for JavaScript the only important thing is that they are there. The reason for this is that the language spec defines that a statement must only start with the function keyword if you declare a named function. Hence, it is against the spec to define an IIFE like that:
function () {}();
The workaround for this is to wrap the entire thing in parentheses, so that the statement does not start with the function keyword anymore. You achieve this by using
(function () {})();
as well as by using:
(function () {}());
Which one you choose is completely arbitrary and hence up to you.
I (personally) put the parentheses around the function, not around the call, i.e. like this one:
(function () {})();
Reason: I want to use the smallest portion of code to be wrapped in something that is only needed for technical reasons, and this is the function definition, not the call. Apart from that the spec says that you can not define a function in that way, it is not about calling the function. Hence, I think it's more clear if you wrap the definition, not the call.
edit
However, in the case of the arrow function in es6, the invocation must be outside of the wrapper. It being inside the wrapper causes an unexpected token error on the opening parenthesis of the invocation. Not totally clear on the mechanics of why this is so.

javascript: reason for declaring and immedieatly calling inline function

So I had an interview where I was asking the purpose of declaring and calling a function immideately, and i couldn't answer it, i.e:
(function(){
// code
})();
What's the reason for doing this?
Object-Oriented JavaScript - Second Edition: One good application of immediate (self-invoking) anonymous functions
is when you want to have some work done without creating extra global
variables. A drawback, of course, is that you cannot execute the same
function twice. This makes immediate functions best suited for one-off
or initialization tasks.
The syntax may look a little scary at first, but all you do is simply
place a function expression inside parentheses followed by another set
of parentheses. The second set says "execute now" and is also the
place to put any arguments that your anonymous function might accept:
(function() {
})();
or
(function() {
}());
are the same:

Strange JavaScript behaviour?

I have a simple function that calls other functions:
function update() {
updateMissiles();
updatePlayer;
updateTurbines();
}
They are similar to each other in every way except updatePlayer will not run if I put brackets on the end of it. This doesn't break any code but I'm still curious why it does that?
I'm guessing there's an Exception in the updatePlayer method and since you're not calling it in the code you pasted above, you're not getting the Exception.
I would open up the Developer Tools for whatever browser you're using and see if there are any JavaScript Exceptions being thrown.
You are confused. updatePlayer; doesn't invoke the updatePlayer function. updatePlayer(); does. Something else is going on in your code.
Without knowing more it's impossible to pinpoint exactly, but as a best guess - in the scope of the update function, the updatePlayer variable is not a function.
Try logging or debugging your javascript to find out what is going on.
A function will run only if you put () after it's name.
If you don't put brackets you'll get the function's content.
For example if you have:
function updatePlayer(){ alert('This is a player');}
And call it without brackets:
alert(updatePlayer);
the alerted output will be
function updatePlayer(){ alert('This is a player');}
This is used if you want to use callback functions.

In JavaScript, what code executes at runtime and what code executes at parsetime?

With objects especially, I don't understand what parts of the object run before initialization, what runs at initialization and what runs sometime after.
EDIT: It seems that parsetime is the wrong word. I guess I should have formulated the question "In the 2-pass read, what gets read the first pass and what gets read the second pass?"
A javascript file is run in a 2-pass read. The first pass parses syntax and collects function definitions, and the second pass actually executes the code. This can be seen by noting that the following code works:
foo();
function foo() {
return 5;
}
but the following doesn't
foo(); // ReferenceError: foo is not defined
foo = function() {
return 5;
}
However, this isn't really useful to know, as there isn't any execution in the first pass. You can't make use of this feature to change your logic at all.
Unlike C++, it is not possible to run logic in the Javascript parser.
I suspect that you're asking which code runs immediately and which code runs when you create each object instance.
The answer is that any code in a function that you call will only run when you call the function, whereas any code outside of a function will run immediately.
Not sure what you ask exactly so I'll just share what I know.
JavaScript functions are "pre loaded" and stored in the browser's memory which means that when you have function declared in the very end of the page and code calling it in the very beginning, it will work.
Note that global variables, meaning any variable assigned outside of a function, are not preloaded, so can be used only after being declared.
All commands outside of a function will be parsed in the order they appear.
JavaScript doesn't really have "runtime", it can only respond to events or have code executed via global timers. Any other code will be parsed and "forgotten".
While JavaScript's direct ancestor is Scheme, JavaScript didn't inherit macros, so the answer is fairly simple: there is never any code run during parse time.
Roughly speaking, Interpreter gets all variables and functions first, and then they get hoisted and executed.
For more detail, I hope these links might be helpful:
http://adripofjavascript.com/blog/drips/variable-and-function-hoisting
https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

Need some help understanding this JavaScript

I have the following strange looking code in a js file and i need some help in understanding whats going on. What im confused about is why is the whole thing put in paranthesis ?. What does that mean ?
(function() {
var someobj = window.someobj = [];
var parentId = '#wrapper';
$(document).ready(function() {
//some code here
});
$(document).ready(function() {
//some code here
}
});
If the code that you provided is complete (with the exception of what is inside the two $(document).ready(function() {}); statements), than this code does nothing and the function is never executed. It's the same with or without the wrapping parenthesis.
By wrapping a function in parenthesis, you can create an anonymous function. However, the function must be executed immediately, or stored in a variable (which would negate the anonymous part). You'll often see this technique to avoid polluting the global scope with variables that are temporary or only used for initialization of a larger application. For example.
(function() {
// Do initialization shtuff
var someLocalVariable = 'value';
})();
// Notice the `();` here after the closing parenthesis.
// This executes the anonymous function.
// This will cause an error since `someLocalVariable` is not
// available in this scope
console.log(someLocalVariable);
So then, what your code is missing is the (); after the closing parenthesis at the end of the function. Here is what your code should (presumably) look like:
(function() {
var someobj = window.someobj = [];
var parentId = '#wrapper';
$(document).ready(function() {
//some code here
});
$(document).ready(function() {
//some code here
});
})();
It does not look like this code is complete. As written, this code will do nothing at all. Are you missing a close paren and an extra set of parentheses at the end?
In JavaScript, there is no module system, and thus no way to create a module with its own top-level definitions that don't conflict with other modules that might be used.
In order to overcome this, people use anonymous function definitions to avoid name conflicts. What you do is create an anonymous function, and execute it immediately.
(function () { /* do stuff */ })();
This creates a function, and then executes it immediately with no arguments. Variables defined using var within that function will not conflict with variables defined anywhere else, and thus you get the equivalent of your own, private namespace, like what a module system would provide.
The outer parentheses are redundant here (there is a typo in your code though, I think you're missing the closing );). Sometimes people will wrap a function in parentheses for clarity when invoking the function immediately, e.g.
(function($) {
//some jQuery code
})(jQuery);
Within the function above, the parameter $ will have the value of the outer jQuery variable. This is done within jQuery and jQuery plugins to prevent the $ symbol clashing with other frameworks.
I'm going to assume that this is actually part of an anonymous function definition and that's why it's in parenthesis. I could see doing this if there was some sort of logic going to make window.someobj change based on different conditions, but have code further along do the same thing.
The parenthesis aren't actually necessary as far that this code goes. This code doesn't seem complete though. The function initializes by setting a variable to some object on the page and then setting another constant. Then there are two seemingly identical triggers that will trigger some code on page load.
Doesn't seem like a very useful piece of code. Is there some larger portion that might shed some light on this?
In JS, You can declare a function and automatically call it afterwards:
( function Test() { alert('test'); } )();
The parentheses define a temporary scope. It is sometimes useful to do so in JavaScript. There are a number of examples and further explanation in John Resig's excellent guide to learning advanced JavaScript:
http://ejohn.org/apps/learn/#57

Categories

Resources