Are the enclosing parenthesis necessary for anonymous functions? [duplicate] - javascript

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 5 years ago.
I've seen JavaScript that looks like this:
function () {
// do something
}()
and recently something like this:
(function () {
// do something
})()
Is there any difference? Both are executed immediately correct?
EDIT:
A note about the first example. The function is being passed to the browser from another application so there was no error from my end. It is throwing an error when run in the browser. After digging in, I've found the application API is passing the function to eval. Both examples above work for me which is why I asked this question.

Both of the functions won't execute immediately. An immediately invoked function expression has parenthesis at the end of it as well. Like this:
(function () {
console.log("not hello");
});
(function () {
console.log("hello");
})();
//^^
The parenthesis enclosing the function turn it to an expression which returns the function itself. Then, you just invoke the returned value (which is the function) with (). Take a look at IIFE.
Edit: After your edit, the first function would just throw SyntaxError: Unexpected token (

Related

javascript named function call throwing error [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
What's the point of naming function expressions if you can't really reference them by the names you give them? [duplicate]
(5 answers)
Closed 5 years ago.
var boo= function foo(){
console.log("I am foo");
}
boo(); // output: I am foo
foo(); // output: Uncaught ReferenceError
I am little confused with javascript named function. Can any one please explain why in above code snippet the foo() function call is throwing the error. Thanks in advance
var boo= function foo(){
There is a clear difference between a function and function expression.
What you have is an expression resolved to a variable. The way you are expecting to work needs to be a function or a variable resolved by a function expression.
From MDN docs
Here is an example of an anonymous function expression (the name is
not used):
var myFunction = function() {
statements
}
It is also possible to provide a name inside the definition in order
to create a named function expression:
var myFunction = function namedFunction(){
statements
}
One of the benefit of creating a named function expression is that in
case we encounted an error, the stack trace will contain the name of
the function, making it easier to find the origin of the error.
As we can see, both example do not start with the function keyword.
Statements involving functions which do not start with function are
function expressions.

What is the difference between writing a function with or without parentheses inside a function in jQuery? [duplicate]

This question already has answers here:
When to use () after a callback function name? [duplicate]
(5 answers)
Closed 6 years ago.
Well I'm starting with jQuery and I'm wondering what is the difference between writing a function with or without parentheses inside a function.
For example if I have the following function:
function test(){
alert("pen pineapple apple pen");
}
This:
$(document).ready(test);
and this:
$(document).ready(test());
both show the same result: "pen pineapple apple pen"
Putting parentheses () at the end of a function causes that function to be invoked immediately, and use its return value in the expression.
This code $(document).ready(test); is using test as a callback function. It essentially says: when the document becomes ready, call the function that I'm providing you with (test).
This code $(document).ready(test()); is immediately invoking the function test, having it return a value, and then passing that value to the ready method. It's possible that test is returning a different function here, which in turn will act as the required callback function. It could also just be an error though, with someone inadvertently including the parentheses when they shouldn't have.

Can you explain this weird function declaration behavior? [duplicate]

This question already has an answer here:
Function call javascript [duplicate]
(1 answer)
Closed 6 years ago.
Can you explain this?
var guessWhat = function(){ console.log('Print this!!!'); };
function guessWhat(){ console.log('Print that???'); }
guessWhat();
// output: Print this!!!
Both are declared on the global scope. Why is the the second line not overriding the first? Is the second function lost in limbo?
function guessWhat(){ console.log('Print that???'); } // declaration
This is a function declaration, it is defined before any code is executed.
var guessWhat = function(){ console.log('Print this!!!'); }; // literal
This is a function literal, it is defined at run-time.
so, the function definition gets loaded first (before any code), and the function literal afterwards, which overrides the first definition, hence this behaviour.
Read more here.

Why is the function with in parenthesis? [duplicate]

This question already has answers here:
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 8 years ago.
Question:
Why is the function wrapped in a parenthesis? I have taken this code out of parenthesis and it works with no trouble.
What is the benefit of having the code in a (function() { ...Code Here...})(); like it is in the following example?
Code:
(function() {
"use strict";
// Doesn't work because strict mode
// enforces the fact that the second example shouldn't work
if (true) {
function fn1() {
// This won't run
console.log("doesn't work -- have a great Die Hard Day XIII");
};
fn1();
}
})();
Code Here: What would sending the JQuery word as a parameter do for this namespace. I know that the reason that the function is enclosed in (...) is to create a namespace. I guess a better question would be as to why one would pass in a variable, but I would imagine that would be in case another namespace needed the variable.
( function( $ ) {
// Init Skrollr
var s = skrollr.init({
render: function(data) {
//Debugging - Log the current scroll position.
//console.log(data.curTop);
}
});
} )( jQuery );
I have taken this code out of parenthesis and it works with no trouble.
That’s not correct; it can’t run (or even be parsed) by itself. JavaScript sees function in a place where a function declaration can be and assumes it’s a function declaration. Parentheses are used to force the context to be an expression. The practice is redundant if it’s unambiguously a function literal – say, in a variable declaration – but many find it more readable. There’s a jsHint option to enforce it, for example.
Because then they are calling it:
(function() { ... })();
^^

JavaScript - ( function () {} () )? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript function vs. ( function() { … } ());
I'm seeing this pattern in several of TodoMVC's JS source:
(function() {
// ...
// ...
}());
What's the specific meaning of this pattern? Note that it is not the self-invoking function which is (function() {})();
What's the specific meaning of this pattern? Note that it is not the self-invoking function which is (function() {})();
You're incorrect, it is an Immediately Invoked Function Expression (IIFE). The parenthesis are just in a different place, but they bind the exact same way.
People often do it in the way you've described to get it to validate JSLint.
It's used for scoping, as JavaScript only has function and global scope (ignoring let).

Categories

Resources