Why javascript function parentheses can not access the outside? [duplicate] - javascript

This question already has answers here:
Why a Name Function Expression not available outside function body [duplicate]
(3 answers)
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I'm curious, why not just javascript function scope it? Why just add a parenthesis can not access it? My guess is that the parentheses and javascript related operations, but do not know exactly why this child principle and design?
(function test(){
console.log( test );
})();
test();//Uncaught ReferenceError: test is not defined IE8- is ok
or
(function test(){
console.log( test );
});
test();//Uncaught ReferenceError: test is not defined IE8- is ok

When you wrap a function in parentheses like you did, it does put it in a new scope.
It also acts like a return value, which is why it can be called as an IIFE, or Immediately Invoking Function Expression.
Another way to re-write it, which will make more sense is like so:
var myFunc = (function test(){
alert('Hello!');
});
myFunc(); // Works!
test(); // Doesn't work!

To learn more about this, you should read about IIFE - Immediately-invoked function expression.
The short version - the function runs in its own scope, unless you pass parameters to it, like so:
(function test(x) {
alert(x); //alerts "yey!";
})("yey!");

Related

Meaning of !function in Javascript self invoking function [duplicate]

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 5 years ago.
Sorry for posting this but !function is not google-able and I did not find it in my JavaScript code.
Here is how Twitter uses it:
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
from https://twitter.com/about/resources/buttons#
It is short-hand or alternative of self-invoking anonymous function:
(function(){
// code
})();
Can be written:
!function(){
// code
}();
You can also use + instead of !.
If you simply did:
function(){
// code
}();
That will create problems, that's why you need to add ! before it which turns the function declaration into function expression.
Quoting docs, section 12.4:
An ExpressionStatement cannot start with the function keyword because
that might make it ambiguous with a FunctionDeclaration.
To better understand the concept, you should check out:
Function Declarations vs. Function Expressions
they're negating the result, not the function itself:
!function( x ){ return x }( true );
!true
false
In reality, it's a slightly compressed form of:
(function(){}())
since it requires 1 less character. The reason it's needed is that you can't call a function declaration directly, e.g. this is invalid:
function(){}()
but adding the ! at the beginning turns it into a function expression and makes it work.
It's usually used to work around a quirk in the JavaScript syntax. This gives a syntax error:
function() {
}();
It's read as a function declaration (like function foo () {}), rather than a function expression. So adding the ! before it, or wrapping it in parentheses, forces the parser to understand that it's an expression.

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.

Why need I wrap anonymous function in parenthesis before calling it in Javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Why this kind of function invocation is wrong in JavaScript?
Is there any reason to wrap anonymous JavaScript functions in braces?
Is there a good explanation why I have to wrap an anonymous functions in parentheses before I can call it, like this:
(function() { alert('foo'); })();
instead of just
function() { alert('foo'); }();
?
There are other languages in which functions are just things you can pass around, like for example Clojure. In Clojure a function call looks like this: (function args), for example: (+ 1 2). You can just substitute an anonymous function anywhere you would normally use a named function: ((fn [a b] (+ a b)) 1 2). In Javascript this seems not to be the case.
Because without parentheses around the function, the code is a bad function declaration and adding the () to its end is a syntax error.
With parentheses around the function, however, you get a function pointer to an anonymous function which can be executed by adding () to its end.

could you explain the function in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
(function(){
var foo = 'Hello world';
})();
i don't know what's use of it? and what's meaning of it/?
On its own it does nothing except declare a variable that isn't used - it should invoke some other functions to do something useful.
That said, what you have is an immediately invoked function expression, i.e. an anonymous function:
function() { ... }
which is invoked with no parameters:
(f....)();
The rationale is two fold:
it allows the function to be defined and called without giving it a name in the global name space
any variables defined within the function are also held within that scope, and don't pollute the global name space.
It's an anonymous function that executes immediately.
The idea is to create a private scope. Often one would return a closure from the anonymous function that retains access to variables created in that scope.
For example
var greet = (function () {
var foo = 'Hello world';
return function () {
alert(foo);
}
}());
greet();
This calls an anonymous function immediately.
Have a look here: What does this “(function(){});”, a function inside brackets, mean in javascript ?

What (function(){})(); mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript ?
(function(){
---this code at here ----
})();
What does (function(){})(); mean? Please explain it to me.
It makes an anonymous function and executes it. You use it to prevent variables from poluting the global scope.
(function(){
var test = "Hello";
})();
alert(test); //test will be undefined here
The function is immediately executed after parsing it.
Well, you use a function expression as a closure which gets executed immediately and 'this code at here' will not pollute global namespace.

Categories