In javascript what does ( ... ) do exactly [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
Recently discussing with a colleague which is best
(function(){...}())
or
(function(){...})()
I got to wondering what ( ... ) actually does at a fundamental level, and what is the difference between what the js engine does in both the above cases. Is one approach theoretically (even if only a tiny amount) faster than the other? If my function returns an object what does ( .. ) do to the object in the first example?
Can anyone explain.
*edit The closest I've got to an explanation on the internet is http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#question-about-surrounding-parentheses, but this stops short, in my view, of explaining why the first example above works at all.

You don't even need parentheses at all. The whole idea of those parentheses is to force a function to be an expression and not a declaration. You can also achieve that like
!function() {
}();
That exclamationmark could also be + or - and some other characters. So, it makes no difference whether you are using the "dog balls" version (your latter one) or not. From a performance aspect, I can't guarantee but I'm 99.9% sure there is zero difference (maybe engine dependent variation at best).
So if we assume that there is no performance difference between those two, its pretty much personal preference which one you use. The Crock many times declared the second version as "dog balls" because you don't wrap the whole expression anymore. I'd agree on that. As mentioned before, the pattern does just force a function expression and it should encapsulate the whole thing for a better readability.

The first example works for exactly the same reason the second example works. There's no real difference. This also works:
!function() { ... } ();
So does this:
var _dont_care_ = function() { ... } ();
The key is to arrange for the function keyword to appear in the statement at a point where the parser knows that it cannot be the start of a function declaration statement. In such cases, the function keyword must be instantiating a function object as a value in an expression.
Statements in JavaScript other than expression statements start with keywords (leave labels aside for the moment). Inside any statement that doesn't start with the function keyword (going out on a limb here), the only thing that function can mean is the instantiation of a function object value.

Related

why a newline between parentheses of two function calls not treat as two statements in js?

why this kind of bad design is made on js? Is there any special reason to design the automatic semicolon insertion like this?
Here is my code, It is not work in js in chrome:
(function(){console.log("abc");})()
(function(){console.log("123");})();
Here is the error:
Uncaught TypeError: (intermediate value)(...) is not a function
I know the right version of this code is :
(function(){console.log("abc");})();
(function(){console.log("123");})();
I just want to know why js syntax is designed so stupid. History reason?
I also add this question as a warning to everybody try to use the automatic semicolon insertion of javascript, please just add ; everywhere it needs, the automatic semicolon insertion of javascript is rubbish. It does not work as your expect.
The exist answer is too complex to my case, so I ask a new one:
https://stackoverflow.com/a/2846298/1586797
Another looks good but not work case 2:
x=1
(function(){console.log("123");})()
The linked question's answers explain the spec's three rules for ASI, for example this one. tl;dr:
If it doesn't work, try with semicolon.
The program should end with a semicolon.
If a statement says "can't put newline here", punish it with semicolon.
Your code does not satisfy any of the criteria.
The first line could return a function, and if so that function should be allowed to be invoked; so ( that the second line begins with is not illegal
The first line is not the last line of the program
There is no restricted syntax here.
Therefore, no automatic semicolon for you.
Some people have thus claimed that while (f(){})() syntax is good IIFE syntax, it might be good to do !f(){}() instead:
!function(){console.log("abc");}()
!function(){console.log("123");}();
This works as intended because ! just negates the (discarded) result of the function application, and also because ! as purely unary operator is an illegal character to continue the first line (i.e. f(){}()! is not a thing). This triggers rule 1, and ASI can take place.
The counterargument is that it is butt-ugly (i.e. for anyone not already familiar with the practice, it takes a while for them to understand the purpose of ! in this idiom).
Your second example is similar in nature: as far as the JS parser is concerned, 1 is a value (the fact that it is an integer and could not possibly be a function is a bit lost to it). Look at this example that syntactically is completely equivalent to yours:
a=function(f) { console.log("A CALLED!"); return f; }
x=a
(function(){console.log("123");})()
# => A CALLED!
123
Here, a is a function, so it can be invoked with function(){console.log("123");} as an argument; it returns function(){console.log("123");} unchanged after printing to the console; then () invokes that return value, and 123 is printed as well. Everything works. Thus, Rule #1 is not triggered, no semicolon for you.
(function(){console.log("abc");})()
(function(){console.log("123");})();
is equivalent to:
(function(){console.log("abc");})()(function(){console.log("123");})();
And is what is usually referred to as function currying.
For IIFEs (immediately invoked function expressions) you need to end with ;
For more on function currying see this post. Obviously your console log functions do not work as currying functions, but the syntax yourFunction(a)(b)(c) is a cool feature of the language that is used for currying.
Your code can be simplified as:
(function(){})()()();
This code will get same error.
The () expect a expression to call.
The first () call the (function(){}), the second () call the (function(){})()'s result, but the result is not a function, so it's wrong.
Without the semicolon those statements are chained. You call the first function and give the second func as argument to the return value of the first one. This could actually work, if the first function had a function as return value.
When you expand the code it becomes more obvious:
var a = function(){console.log("abc");};
var b = function(){console.log("123");}
(a)()
(b)();
the last two lines become:
(a)()(b)();
this is equivalent to
var x = a();
x(b);
since a does not return anything, it cannot call it as function with b as argument.
I think this will be clearer if you use this:
x=1
(function(){console.log("123");})()
The error states 1 is not a function. Makes it clear that (function...) is treated like the argument of a function call to 1:
x=1(function(){console.log("123");})()
Because ()() is self-invoking function and ();() are two differnt functions and interpreter is interpreting it accordingly.
Here two pieces of code are totally different for an interpreter.
(function(){console.log("abc");})()(function(){console.log("123");})();
and
(function(){console.log("abc");})();(function(){console.log("123");})();
however, this code will work fine
var a=12
var b=10
console.log(a+b)
Long answer sort :
(function(){console.log("abc");})()
is trying to immediately-invoke the preceding expression which is
(function(){console.log("123");})();
Which would be the return value of the preceding IIFE.
IIFEs can act differently in the missing semicolon situation. That is why we see code as follows:
;(function() {
console.log('abc');
})()
Please have a look of details description here : https://gist.github.com/khellang/8518964

Syntax rules for parentheses in JavaScript

I'm curious about the syntax rules for parentheses in certain circumstances in JavaScript, such as in wrapping bits of code. I'm very familiar with using them for conditions, like if(this) that and to call functions, but there are a couple of other ways I've noticed myself using them and I don't actually know what the rule is, or if they're even connected.
What I've seen:
I've seen them used to wrap a function in IIFEs -the outside pair in (() => { do something })();, and also in implicit return statements from arrow functions when you want to break the line, like in React stateless functional components:
() => (
<div>
Hello World
</div>
);
I'm also aware that you can wrap a condition in multiple parentheses (for no good reason) and it doesn't break anything: if(((true))).
What I want to know:
I've discovered that I can't use parenthesis to organize my code just wherever I want to.
Are these all related? What is the rule for how/when you can wrap things? Is it all for organization's sake or is there sometimes a change in functionality (I'm thinking IIFEs in particular here)?
Thanks for any clarity on this!
There are some basic things, all different, that parentheses do:
Group subexpressions within a larger expression;
Delineate portions of some statement syntaxes (for, while, etc)
Delineate function call parameters
Delineate formal parameters in function declarations
It therefore does not really make sense to think about how parentheses can be used in a general sense, except in the first case (subexpression grouping). In that case, they work like parentheses in ordinary algebra.
In the other cases, the parentheses are part of the syntax, and they're not optional. Unfortunately in running code you can't tell one sort of parenthesis from another without simply knowing the syntax. So in
someFunction(x, (y + 1), z)
The parentheses around y + 1 are optional, and part of the expression grammar, while those around the overall list of function arguments are not optional, being required for that subexpression to be a function call.
There's really no shortcut to becoming familiar with the details of JavaScript statement syntax.

What is the community's intention of putting a couple of parenthesis around an anonymous function declaration in JavaScript? [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 5 years ago.
What is the semantic difference between these two snippets of code?
Example 1
var x = (function () {} ());
Example 2
var x = (function () {} )();
The difference in writing is where we put our parenthesis pair () which tells the JavaScript interpreter to execute the code block at once. Technically, there is no difference. If I may rephrase the wording of my question and eliminate the word "semantic", then the new question has already been answered and elaborated upon here: https://stackoverflow.com/a/6645915/1268003
But, the semantic part is my dilemma and what I hope this thread could shine some light on. Due to it being "semantic", there can be no objective answer and my question is admittedly on the borderline of not being valid according to the FAQ of Stackoverflow. However, I can argue for the validity of this question which just might happen in the comments. For now, lets move on.
Defining the problem
The absolute vast majority of all JavaScripters out there seems to use example 2. Actually, I haven't yet found one exception to that rule (or where have I been lately?). jQuery plugin developers in particular, write code like so:
Example 3 (see example of an example)
(function ($) {} )(jQuery);
My bible, JavaScript: The Definitive Guide , doesn't use this practice at all - not once. Author David Flanagan sticks to example 1 (page 249 is the place where author comments this practice).
Never mind which construct, added parenthesis all have one and only one intention: To maximize readability. To clarify. Then, may I ask, clarify what?
My reasoning
When writing a closure in JavaScript, we're defining a local variable in a function that is not supposed to be accessible from code outside. For the most part and due to context, our function is an anonymous one that isn't bound to an identifier. Like so:
Example 4
function () { var local = "Local variable!"; }
Again due to context and what is usually the practice, we want to execute that snippet of code at once. So we throw in a couple of parenthesis. This will tell the JavaScript interpreter to run the function:
Example 5
function () {} ()
To clarify this in code, best practice is to add a couple of parenthesis, in a way this also clarifies the closure:
Example 6
(function () {} ())
This is an exact replica of example 1. My reasoning thus gives that example 1is the way we "should" write code. Whenever I choose to use example 2, I only clarify the use of a closure, not the fact that our anonymous function is executed at once. But by the smallest of efforts to place our clarification-parenthesis on the outside of the entire code snippet, we can catch both.
Yes I can critique my reasoning. In example 3, I find it appealing to think "hey, outside reference is copied to an alias on the inside". The alternative:
Example 7
(function ($) {} (jQuery))
..isn't as clear in this particular regard. However, example 2 doesn't use this pass-by-value technique. Personally, for the most part when I write closures, I don't have to pass anything in. And still, if we are allowed to be fundamentalist about it, the jQuery plugin practice never clarifies the immediate execution of our anonymous function.
Example 1 users
If my reasoning holds true, why is it then that the entire community out there use example 1? Is their sole intention to only cast one of two clarifications? Maybe just maybe, they don't even have a purpose but are following the lead of a mere tradition of which purpose we might not be able to explain? I haven't yet written a jQuery plugin, or used example 2 because I began my career reading the bible. But if you are among the many who use example 1 and have a reasoning for it, please share =)
Why? Readability
Many things are done in code because of the mantra of "Readability". It is invaluable in writing code. Your code should be easily inherited by another developer.
You forgot one
Or zero, as it were.
Example 0
var x = function(){ }();
And here is why people don't use that: it is hard to read. Usually these closures become very large, very quick. Someone shouldn't have to get to the very end of the closure to determine that it is just a variable named x with no self execution - such as var x = function(){}; To this end, developers wrapped their self executing closures with parenthesis: var selfExecuting = (function(){})();, or even plainly (function(){})(); so that from line 1 it was obvious that this was self executing. It also means that if you come across a function like this: var notExecuting = function(){}; you can generally assume at line 1 that it is not self executing.
Readability is very important when coding. It is important for maintenance. It is important for consistency. It is important for documentation.
Although, keep in mind, development code should not be production code.

if..else vs if(){return} [duplicate]

This question already has answers here:
Using 'return' instead of 'else' in JavaScript
(13 answers)
Closed 5 years ago.
In the following example - given that the return value isn't of any importance - is there a reason to prefer either method over the other?
// Method 1
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
} else {
// or here
}
return true;
}
// Method 2
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
return true;
}
// or here
return true;
}
It seems that best practices (mostly by places I've worked for) is to set default values at the top of a method or function and only change those values if some condition occurs. Thus, the use of else is not needed so Method 2 is preferred.
Since the example is JavaScript, special attention needs to be paid in regards to code size. So Method 2 would create less code for the same functionality, furthering its argument as the preferred.
However, if you have more than 2 possible conditions, an else or else if cannot be avoided. However, most places I've worked prefer a Switch Case in these situations.
I would prefer Method 1 because it is less confusing to read. Also, less duplicate code.
I would base my decision on clarity of code and readability, i.e.:
Choose method 1 when you need to do more stuff in the block after the if-block.
Choose method 2 when you only need two blocks of code, it's then clearer to read
Choose method 1 again in cases where you explicitly think your readers wouldn't understand your cryptic code without the word "else"; this is common when the blocks become larger than a few lines.
Many of today's programmers consider less indentation easier to read and I agree. In which case general preference should go to using the second method.
I would recommend method 1 as it is more readable and self documented.
Any modern browser's interpreter should eliminate any performance advantage in either direction.
There are a couple of reasons method 1 is preferable that haven't been mentioned yet. Having a single point of exit makes any future modifications that require an action common to both branches easier and less likely to be buggy (because the author missed the early return. Similarly, in some cases it makes debugging easier, by providing a common place to put a breakpoint or alert().
Readability here really depends on the role of the function.
If this function will ALWAYS return true, then I would prefer the Method 1 It is clear because it only returns in one place, and it is easy to see it will always be true.
In the above case, Method 2 is more confusing. It returns in multiple places, and is more confusing thusly. Consider a developer unnecessarily traversing possible branches and then seeing how they affect the return value. In this simple case, it is not as big of a deal, but when you get more elaborate conditionals, I would really avoid this approach.
I would only use Method 2 if you have very little code in the if block. Such as something that would deal with an edge case.
Hope that helps.

JavaScript object definition conditionals - which is better?

I've come across two different ways to define/name objects and functions in JavaScript that first check for the existence of the name before using it. The issue is, I don't know which one is better (from speed and usability standpoints) and it's impossible to use the boolean operators in a Google search to figure it out.
The first one I see most often:
var myNewObject = myNewObject ? myNewObject : function () {
// Code goes here.
};
The second one seems more concise, but I've only seen it one or two places, so I don't know if there's a standard or even a name for it:
var myNewObject = myNewObject || function() {
// Code goes here.
};
Functionally, they both do the same thing and they both seem to work in every browser I can test in. My question is this - which is better and why? Also, while the first definition is essentially a single-line conditional ... what is the second one called?
I would choose the latter if only for the fact that you type myNewObject twice instead of thrice.
Also, while the first definition is essentially a single-line conditional ... what is the second one called?
Short-circuit evaluation
I would use the second example, which is described as (Minimum Eval). Its simpler and seems more readable.
It's just like getting an event from onClick method across multiple browsers.
element.onclick = function (evt) {
evt = evt || window.event
}
The latter, it's similar to the null coalesce operator in c# ?? when used in that manner
see: Is there a "null coalescing" operator in JavaScript?
FWIW I see the second approach more often, and (for my part) I feel it's more clear, concise, and idiomatic.
Both methods work.
But I think the most optimized version is to simply use a normal if test like:
if(!myNewObject)
myNewObject = ...
Doing in any one of the method you suggest in your answer, it might involve an unnecessary reassignment every time the function/object is already defined. I mean if myNewObject is already defined, the JavaScript runtime would have to perform an unnecessary reassignment myNewObject = myNewObject (unless the runtime doesn't optimize it out).
On Mozilla website they suggest to use a simple if, view this.

Categories