difference between javascript function declaration [duplicate] - javascript

This question already has an answer here:
Anonymous function vs normal function
(1 answer)
Closed 9 years ago.
I know this type of question gets asked a lot, but I haven't seen any question with this type of declaration
(function(){
myFuncName=function(myVar){
// some logic
};
}());
how does that differ from
function myFuncName(myVar){
// some logic
}

The first one is an anonymous function and there is no way you can reference to and call it later on, so you just executes instantly ( ) once it had been created!
(function(){
alert(1)
}())
The second one is a reference function that you can call it anytime later. It wont gets executed unless you call it explicitly

What your doing is creating an anonymous function that also has a closure in it. Read more about closures here.
Basically a closure means that you have declared a function inside of another function. Which will let you access local variables after the first function exits.
Normally you would not be able to do this since they would be out of scope.
As for the other part. You can find a very useful guide to what's happening here Why do you need to invoke an anonymous function on the same line?.
To sum it up though, you have created an anonymous self-invoking function expression.
The self-invoking comes from the fact that () immediately follows the function expression.

Here's a link which explains the the function declarations in javascript.

Related

Javascript function declaration - different behaviour? [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 5 years ago.
By trying to override a function I occurred in this odd behaviour. I hope to find an answer after having searched and read about function declaration methods without success.
In a script, if I declare this
var someFunction = function(){
alert("a");
}
someFunction();
someFunction = function(){
alert("b");
}
By calling someFunction I will have an output of "a"
But if I declare the two functions in this way
function someFunction(){
alert("a");
}
someFunction();
function someFunction(){
alert("b");
}
My output will be "b"
What is the difference here? I understand the first example is assigning to a variable an anonymous function. But the second example is totally unexpected and new to me.
I tested on all browsers and the output is the same.
The difference is the fact you are calling an anonymous function in the first example, Javascript gets evaluated top to bottom. In the case of an anonymous function it isn't actually executed UNTIL it is called later on.

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

With jQuery, what is the point of encapsulating a function in round brackets? [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I see this in some HTML files that use jQuery, at the bottom:
(function() {
setTimeout(function(){window.scrollTo(0,0);},0);
})();
What does it mean to put the whole function in round brackets?
The code you gave as example is a self-executing anonymous function.
You can read more about them here.
Relevant text from that article:
What’s useful here is that JavaScript has function level scoping. All variables and functions defined within the anonymous function aren’t available to the code outside of it, effectively using closure to seal itself from the outside world.
(function() {})(); means it is self executing anonymous function. It get called immediately when java script get rendered. More details you can search it.
setTimeout is a function which accepts two parameters:
First parameter: A function
Second parameter: an integer value in milliseconds.
By calling the setTimeout function, the function from first parameter will be called/invoked after the amount of time specified in the second parameter.

Function excuted before creation [duplicate]

This question already has answers here:
Why can I use a function before it's defined in JavaScript?
(7 answers)
Closed 9 years ago.
I am no JavaScript expert, but I found some code like this
a();
function a(){
alert('a');
}
and I was surprised to find it works (I think something like that will not work in Python). I expected that the function a can't be executed before being created. How does interpreter work and why functions can be called before declaration?
This happens because of variable hoisting.
See this answer for more info
JavaScript 'hoisting'
Some docs about this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting
If you type it like this, it won't work:
a();
a = function(){
alert('a');
}
Code that is within functions and objects will be run whenever that
function or object is called. If it is called from code that is
directly in the head or body of the page then its place in the
execution order is effectively the spot where the function or object
is called from the direct code.
See the reference here.
And in our case the function will give the error as you can see the example here.
It's because function a() is declared via Function Declaration syntax, and Function Declaration are executed right after the script is parsed. With other syntax, Function Expression, like this:
var b = function(){
alert('b');
}
it won't work (see example).
More info: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

What means construction (function () { ... } ) () [duplicate]

This question already has answers here:
What is this practice called in JavaScript?
(7 answers)
Closed 9 years ago.
What means this construction in JavaScript :
(function (){
alert("bla");
})();
?
The acronym for this pattern is an "IIFE" or an Immediately Invoked Function Expression.
It basically creates an anonymous function function(){}
function(){alert("bla");}
then wraps it as an expression ()
(function(){alert("bla");})
then executes it ()
(function(){alert("bla");})()
Note that at this point, you can pass arguments in as well like this:
(function(text){alert(text);})("bla")
It's an anonymous block - declare an anonymous function then execute it immediately, meaning that any variables declared in the block are not seen outside it. In this case with the alert() it makes no difference.
It is an anonymous function which will be excecuted one time automatically after loading
JS function definition : meaning of the last parentheses
Here you define an anonymous function to be executed immediately.
The function declaration is expressed as a function expression, which may be anonymous and returns the value of the newly created function. It returns the value of the newly created function, so by adding parenthesis after it, you may immediately invoke it.
You define a an anonymous function, which you immediately call.
See also What is the purpose of a self executing function in javascript? for an explanation of the purpose of the construct, which is, in short, to keep names private to the code wrapped in the anonymous function.

Categories