This may be a silly question, but why are function arguments in JavaScript not preceded by the var keyword?
Why:
function fooAnything(anything) {
return 'foo' + anyThing;
}
And not:
function fooAnything(var anything) {
return 'foo' + anyThing;
}
I have a feeling the answer is because that's what the Spec says but still...
Most dynamicaly-typed programming languages don't have explicit vars in the argument list. The purpose of the var keyword is to differentiate between "I am setting an existing variable" and "I am creating a new variable" as in
var x = 17; //new variable
x = 18; //old variable
(Only few languages, like Python, go away with the var completely but there are some issues with, for example, closures and accidental typos so var is still widespread)
But in an argument list you cannot assign to existing variables so the previous ambiguity does not need to be resolved. Therefore, a var declaration in the arguments list would be nothing more then redundant boilerplate. (and redundant boilerplate is bad - see COBOL in exibit A)
You are probably getting your idea from C or Java but in their case type declarations double up as variable declarations and the cruft in the argument lists is for the types and not for the declarations.
We can even get away with a "typeless, varless" argument list in some typed languages too. In Haskell, for example, types can be inferred so you don't need to write them down on the argument list. Because of this the argument list consists of just the variable names and as in Javascript's case we don't need to put the extraneous "let" (Haskell's equivalent to "var") in there:
f a b = --arguments are still variables,
-- but we don't need "let" or type definitions
let n = a + b in --extra variables still need to be declared with "let"
n + 17
It would be a redundant use of the var keyword. Items that appear in the parentheses that follow a function name declaration are explicitly parameters for the function.
The var keyword declares the scope of the variable. A function argument also introduces the scope for that argument. Hence there's no need for it, since it serves the same function.
I think the question comes up because we're used to seeing function bla (int i) in many languages. The same, syntactically, as the int i; somewhere in the function body to declare a variable. The two ints are however not doing the same; the first defines the type, the second defines type and the scope. If you don't have to declare the type, the scope-declaration still needs to happen (which is why we have var in the second case) but there is no information needed in front of arguments.
Related
TLDR: Why are function parameters not treated as var declarations?
Using var, redeclaring a variable declared using var has no effect. The original declaration remains in effect.
However, using var in this way will mask a parameter of the same name.
Why is the language designed like this?
In the following, variable var bar is treated as a new declaration and not a redeclaration of parameter bar.
function foo(bar = 0, bam = () => bar) {
var bar = 1
return bam()
}
console.log(foo()) // 0
Is it designed like this because arguments and local variables are semantically fundamentally different, and fall into two categories?
I might have expected parameters to be treated like var declarations, but they aren't. They appear to be in their own "box" on the scope chain.
So the scope chain of a function looks like this:
function body >> parameter list >> outer function body >> outer parameter list >> ... global scope
Are arguments and local variables semantically fundamentally different, and fall into two categories?
No, not really. In fact, in many cases they are indistinguishable, creating variables in the same scope - just not here in the example you gave.
I might have expected parameters to be treated like var declarations, but they aren't. They appear to be in their own "box" on the scope chain.
Yes. That's because you are using default initialisers in your parameter declaration, which gives the parameters their own scope, and the function body scope is a child of that. Still, vars are getting declared in that body scope (not getting hoisted).
It might be fitting to say that parameters are treated like let declarations since ES6, except where they need to be treated as var declarations to preserve backwards compatibility (allowing re-declarations). See here or there for details.
The concept of variable hoisting and clouser in javascript states that variables remembers enviornment in which they are created.
Now lets have a look in your example line by line
function foo(bar = 0, bam = () => bar) { // here bar 0, and function `bam` will remember bar value as 0 whenever it gets called
And when you are reassigning bar to 1 in function foo, function bam will not update it. As both function have different scopes.
So as per the javascript concept, this is correct and desired behaviour.
Update:
function foo(bar = 0, bam = () => bar) {
bar = 1
return bam()
}
console.log(foo()) // 1
This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 7 years ago.
I'm reading up on JavaScript IIFE and so far the understand concept, but I am wondering about the outside parenthesis. Specifically, why are they required? For example,
(function() {var msg='I love JavaScript'; console.log(msg);}());
works great, but
function() {var msg='I love JavaScript'; console.log(msg);}();
generates a syntax error. Why? There are lots of discussions on IIFE, but I'm not seeing a clear explanation about why the parentheses are required.
There are two ways to create functions in JavaScript (well, 3, but let's ignore new Function()). You can either write a function declaration or write a function expression.
A function declaration in itself is a statement and statements by themselves don't return values (let's also ignore how the debugging console or Node.js REPL print return values of statements). A function expression however is a proper expression and expressions in JavaScript returns values that can be immediately used.
Now, you may have seen people saying that the following is a function expression:
var x = function () {};
It may be tempting to conclude that the syntax:
function () {};
is what makes it an expression. But that's wrong. The syntax above is what makes it an anonymous function. And anonymous functions can either be a declaration or an expression. What makes it an expression is this syntax:
var x = ...
That is, everything to the right of an = sign is an expression. Expressions make it easier to write math formulas in programming languages. So in general everywhere that math is expected to be processed is an expression.
Some of the forms of expressions in JavaScript include:
everything to the right of an = operator
things in braces () that are not function call braces
everything to the right of a math operator (+,-,*,/)
all the arguments to the ternary operator .. ? .. : ..
When you write:
function () {}
it is a declaration and does not return a value (the declared function). Therefore trying to call the non-result is an error.
But when you write:
(function () {})
it is an expression and returns a value (the declared function) which may be used immediately (for example, may be called or may be assigned).
Note the rules for what counts as expressions above. From that it follows that braces are not the only things that you can use to construct an IIFE. Below are valid ways for constructing IIFEs (because we write function expressions):
tmp=function(){}()
+function(){}()
-function(){}()
0/function(){}()
0*function(){}()
0?0:function(){}()
(function(){}())
(function(){})()
You may actually see one of the above non-standard forms (particularly the + version) in third-party libraries, because they want to save one byte. But I strongly advise you to only use the brace forms (either are fine), because they are widely recognized as IIFEs by other programmers.
The version of IIFE that is wrapped in parenthesis works, because this marks the declaration of the internal function declaration as an expression.
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
For more detailed explanation please see:
Advanced JavaScript: Why is this function wrapped in parentheses?
HINT:
The invocation operator (()) only works with expressions, not declarations.
This will be a long-winded answer, but will give you the necessary background. In JavaScript there are two ways functions can be defined:
A function definition (the classical kind)
function foo() {
//why do we always use
}
and then the more obscure type, a function expression
var bar = function() {
//foo and bar
};
In essence the same thing is going on at execution. A function object is created, memory is allocated, and an identifier is bound to the function. The difference is in the syntax. The former is itself a statement which declares a new function, the latter is an expression.
The function expression gives us the ability to insert a function any place where a normal expression would be expected. This lends its way to anonymous functions and callbacks. Take for instance
setTimeout(500, function() {
//for examples
});
Here, the anonymous function will execute whenever setTimeout says so. If we want to execute a function expression immediately, however, we need to ensure the syntax is recognizable as an expression, otherwise we have ambiguity as to whether of not we mean a function expression or statement.
var fourteen = function sumOfSquares() {
var value = 0;
for (var i = 0; i < 4; i++)
value += i * i;
return value;
}();
Here sumOfSquares is immediately invoked because it can be recognized as an expression. fourteen becomes 14 and sumOfSquares is garbage-collected. In your example, the grouping operator () coerces its content into an expression, therefore the function is an expression and can be called immediately as such.
One important thing to note about the difference between my first foo and bar example though is hoisting. If you don't know what that it is, a quick Google search or two should tell you, but the quick and dirty definition is that hoisting is JavaScript's behavior to bring declarations (variables and functions) to the top of a scope. These declarations usually only hoist the identifier but not its initialized value, so the entire scope will be able to see the variable/function before it is assigned a value.
With function definitions this is not the case, here the entire declaration is hoisted and will be visible throughout the containing scope.
console.log("lose your " + function() {
fiz(); //will execute fiz
buzz(); //throws TypeError
function fiz() {
console.log("lose your scoping,");
}
var buzz = function() {
console.log("and win forever");
};
return "sanity";
}()); //prints "lose your scoping, lose your sanity"
I've wanted to switch to Coffeescript for a while now and yesterday I thought I'm finally sold but then I stumbled across Armin Ronachers article on shadowing in Coffeescript.
Coffeescript indeed now abandoned shadowing, an example of that problem would be if you use the same iterator for nested loops.
var arr, hab, i;
arr = [[1, 2], [1, 2, 3], [1, 2, 3]];
for(var i = 0; i < arr.length; i++){
var subArr = arr[i];
(function(){
for(var i = 0; i < subArr.length; i++){
console.log(subArr[i]);
}
})();
}
Because cs only declares variables once I wouldn't be able to do this within coffeescript
Shadowing has been intentionally removed and I'd like to understand why the cs-authors would want to get rid of such a feature?
Update: Here is a better example of why Shadowing is important, derived from an issue regarding this problem on github
PS: I'm not looking for an answer that tells me that I can just insert plain Javascript with backticks.
If you read the discussion on this ticket, you can see Jeremy Ashkenas, the creator of CoffeeScript, explaining some of the reasoning between forbidding explicit shadowing:
We all know that dynamic scope is bad, compared to lexical scope, because it makes it difficult to reason about the value of your variables. With dynamic scope, you can't determine the value of a variable by reading the surrounding source code, because the value depends entirely on the environment at the time the function is called. If variable shadowing is allowed and encouraged, you can't determine the value of a variable without tracking backwards in the source to the closest var variable, because the exact same identifier for a local variable can have completely different values in adjacent scopes. In all cases, when you want to shadow a variable, you can accomplish the same thing by simply choosing a more appropriate name. It's much easier to reason about your code if a local variable name has a single value within the entire lexical scope, and shadowing is forbidden.
So it's a very deliberate choice for CoffeeScript to kill two birds with one stone -- simplifying the language by removing the "var" concept, and forbidding shadowed variables as the natural consequence.
If you search "scope" or "shadowing" in the CoffeeScript issues, you can see that this comes up all the time. I will not opine here, but the gist is that the CoffeeScript Creators believe it leads to simpler code that is less error-prone.
Okay, I will opine for a little bit: shadowing doesn't matter. You can come up with contrived examples that show why either approach is better. The fact is that, with shadowing or not, you need to search "up" the scope chain to understand the life of a variable. If you explicitly declare your variables ala JavaScript, you might be able to short-circuit sooner. But it doesn't matter. If you're ever unsure of what variables are in scope in a given function, you're doing it wrong.
Shadowing is possible in CoffeeScript, without including JavaScript. If you ever actually need a variable that you know is locally scoped, you can get it:
x = 15
do (x = 10) ->
console.log x
console.log x
So on the off-chance that this comes up in practice, there's a fairly simple workaround.
Personally, I prefer the explicitly-declare-every-variable approach, and will offer the following as my "argument":
doSomething = ->
...
someCallback = ->
...
whatever = ->
...
x = 10
...
This works great. Then all of a sudden an intern comes along and adds this line:
x = 20
doSomething = ->
...
someCallback = ->
...
whatever = ->
...
x = 10
...
And bam, the code is broken, but the breakage doesn't show up until way later. Whoops! With var, that wouldn't have happened. But with "usually implicit scoping unless you specify otherwise", it would have. So. Anyway.
I work at a company that uses CoffeeScript on the client and server, and I have never heard of this happening in practice. I think the amount of time saved in not having to type the word var everywhere is greater than the amount of time lost to scoping bugs (that never come up).
Edit:
Since writing this answer, I have seen this bug happen two times in actual code. Each time it's happened, it's been extremely annoying and difficult to debug. My feelings have changed to think that CoffeeScript's choice is bad times all around.
Some CoffeeScript-like JS alternatives, such as LiveScript and coco, use two different assignment operators for this: = to declare variables and := to modify variables in outer scopes. This seems like a more-complicated solution than just preserving the var keyword, and something that also won't hold up well once let is widely usable.
The main issue here isn't shadowing, its CoffeeScript conflating variable initialization and variable reassignment and not allowing the programmer to specify their intent exactly
When the coffee-script compiler sees x = 1, it has no idea whether you meant
I want a new variable, but I forgot I'm already using that name in an upper scope
or
I want to reassign a value to a variable I originally created at the top of my file
This is not how you forbid shadowing in a language. This is how you make a language that punishes users who accidentally reuse a variable name with subtle and hard to detect bugs.
CoffeeScript could've been designed to forbid shadowing but keep declaration and assignment separate by keeping var. The compiler would simply complain about this code:
var x = blah()
var test = ->
var x = 0
with "Variable x already exists (line 4)"
but it would also complain about this code:
x = blah()
test = ->
x = 0;
with "Variable x doesn't exist (line 1)"
However, since var was removed, the compiler has no idea whether you meant meant "declare" or "reassign" and can't help.
Using the same syntax for two different things is not "simpler", even though it may look like it is. I recommend Rich Hickey's talk, Simple made easy where he goes in depth why this is so.
Because cs only declares variables once the loop will not work as intended.
What is the intended way for those loops to work? The condition in while i = 0 < arr.length will always be true if the arr is not empty, so it will be an infinite loop. Even if it's only one while loop that won't work as intended (assuming infinite loops are not what you're looking for):
# This is an infinite loop; don't run it.
while i = 0 < arr.length
console.log arr[i]
i++
The correct way of iterating arrays sequentially is using the for ... in construct:
arr = [[1,2], [1,2,3], [1,2,3]]
for hab in arr
# IDK what "hab" means.
for habElement in hab
console.log habElement
I know that this answer sound like going off on a tangent; that the main point is why CS discourages variable shadowing. But if examples are to be used to argument in favour of or against something, the examples ought to be good. This example doesn't help the idea that variable shadowing should be encouraged.
Update (actual answer)
About the variable shadowing issue, one thing that it worth clarifying is that the discussion is about whether variable shadowing should be allowed between different function scopes, not blocks. Within the same function scope, variables will hoist the whole scope, no matter where they are first assigned; this semantic is inherited from JS:
->
console.log a # No ReferenceError is thrown, as "a" exists in this scope.
a = 5
->
if someCondition()
a = something()
console.log a # "a" will refer to the same variable as above, as the if
# statement does not introduce a new scope.
The question that is sometimes asked is why not adding a way to explicitly declare the scope of a variable, like a let keyword (thus shadowing other variables with the same name in enclosing scopes), or make = always introduce a new variable in that scope, and have something like := to assign variables from enclosing scopes without declaring one in the current scope. The motivation for this would be to avoid this kind of errors:
user = ... # The current user of the application; very important!
# ...
# Many lines after that...
# ...
notifyUsers = (users) ->
for user in users # HO NO! The current user gets overridden by this loop that has nothing to do with it!
user.notify something
CoffeeScript's argument for not having a special syntax for shadowing variables is that you simply shouldn't do this kind of thing. Name your variables clearly. Because even if shadowing would be allowed it would be very confusing to have two variables with two different meanings with the same name, one in an inner scope and one in an enclosing scope.
Use adequate variable names according to how much context you have: if you have little context, e.g. a top-level variable, you'll probably need a very specific name to describe it, like currentGameState (especially if it's not a constant and its value will change with time); if you have more context, you can get away with using less descriptive names (because the context is already there), like loop variables: killedEnemies.forEach (e) -> e.die().
If you want to know more about this design decision, you may be interested in reading Jeremy Ashkenas opinions in these HackerNews threads: link, link; or in the many CoffeeScript issues where this topic is discussed: #1121, #2697 and others.
We have received some JavaScript from an agency that looks wrong, but works.
For some reason they are adding square brackets ([, ]) around variables, like this:
var some_variable = 'to=' + [other_variable];
This works, but the square brackets seem completely superfluous.
Is there a purpose of using this syntax or is it technically incorrect, but ignored by the browser?
Just in case anyone else arrives here while trying to find out what some weird/new syntax involving [square brackets] (seen in someone else's Javascript) might possibly be, like I was...
Nowadays, with ES6, we also have [] used on the left-hand side for destructuring arrays, e.g.
const names = ['Luke', 'Eva', 'Phil'];
const [first] = names;
console.log(first); // 'Luke'
const [first, second] = names;
console.log(first, second); // 'Luke' 'Eva'
For further info see http://www.deadcoderising.com/2017-03-28-es6-destructuring-an-elegant-way-of-extracting-data-from-arrays-and-objects-in-javascript/ or google 'es6 destructuring'.
Square brackets means new Array.
var ar=new Array("a","b");
var ar=["a","b"]; //Equal to the syntax above
in that situation there's no difference if you use square brackets or not because if it's an array it is converted to string, but if you delete the brackets it takes less time because it doesn't have to build a new array and convert it but it works with a simple string.
Even without changing the Array prototype there are differences:
var other_variable;
var some_variable = 'to=' + [other_variable];
If other_variable is undefined, the return value with the array is "to=".
Without the array, the return value is "to=undefined".
b = "bar" + ["foo"]
This is syntactically correct, but indeed very, very, superfluous. This is how it works:
["foo"]
JavaScript takes the string "foo" and converts it to an array with one element, "foo":
"bar" + ["foo"]
when + is used, and one of the operands is a string, "bar" in this case, JavaScript converts the second one to a string. Since operand two is an Array, the Array.toString method is called, which, by default, returns all elements joined by a comma. We have one element, and the result will be equal to this element, i.e., in this context "foo" is equivalent to ["foo"].
If you redefine Array.toString you can see better what's going on:
alert("bar" + ["foo"])
Array.prototype.toString = function() { return "???"; }
alert("bar" + ["foo"])
I bet someone told that person:
"Do the string concatenation with an array, it's faster!"
Meaning:
var some_variable = ['to=', other_variable].join("");
Which is apparently faster for lots of concatenations, but totally irrelevant, as that code will probably run just once anyway. Premature_optimization = sqrt(all_evil)!
And the poor chap did that other irrelevant thing...
I love people.
It's possible to construct a situation where this:
var some_variable = 'to=' + other_variable;
and this:
var some_variable = 'to=' + [other_variable];
produce different results. Specifically, if the Array.prototype.toString() method (or, I suppose, the Array.prototype.join() method) has been changed from its default, anything could happen. For example, extra functionality could be added to the Array.prototype.toString() method to generate logging information, do some lookups, or anything really.
The likelihood that this has been done is slim, I'd imagine, but it needs to be mentioned for completeness.
May be this ..
Global Variable access with the Square Bracket Notation
The square bracket notation requires that there be some sort of object reference to the left of the brackets.
["document"] //Array literal, not a Property Accessor!
-will produce an error if an attempt is made to assign a value to it, as it will be treated as an Array literal, if an attempt to read from it is made the one element array containing the string within the brackets is returned. Global variables are normally referenced by their one identifier alone. This would seem to exclude global variables from the possibility of being referenced using a string that held their identifier name or an expression that built, or returned, their name. However, javascript global variables (and global function names for that matter) are properties of a global object. Any identifier that holds a reference to the global object can be used to the left of the square brackets to form a property accessor that refers to a global variable.
In a web browser the global object is the window (or frame) in which the script is running. Each window (or frame) object contains a number of properties, at least two of which are references to the window (global object) itself. These properties are 'window' and 'self'. These property names can be used as the identifier to the left of the square brackets when referring to global variables. So given a global variable defined as:-
var anyName = 0;
that global variable can be referenced as:-
window["anyName"]
As with any other use of the square bracket notation, the string within the brackets can be held in a variable or constructed/returned by an expression.
Code that is executing in the global context, the code within global functions (except Object constructors invoked with the new keyword) and inline code outside of any functions, could also use the this keyword to refer to the global object. The this keyword refers to an object depending on the execution context. For code executing in the global context this is the global object (on a web browser, the window object). As a result, the above variable could be referred to as this["anyName"], but only in code that is executing in the global context.
However, using the this keyword is very likely to be confusing, especially in scripts that include custom javascript objects where the methods (and constructors) of those objects would be using this to refer to their own object instances.
Some javascript implementations do not have a property of the global object that refers to the global object. Rather than trying to use the this keyword to access global variables it is possible to create your own global variable that refers to the global object.
var myGlobal = this;
executed as inline code at the start of a script will assign a reference to the global object (this in that context). From then on all global variables can be referenced with square bracket notation as:-
myGlobal["anyName"];
and expect myGlobal to refer to the global object from any execution context.
This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 8 years ago.
In the YUI library examples, you can find many uses of this construct:
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event,
layout = null,
...
})();
I think the last couple of parentheses are to execute the function just after the declaration.
... But what about the previous set of parentheses surrounding the function declaration?
I think it is a matter of scope; that's to hide inside variables to outside functions and possibly global objects. Is it? More generally, what are the mechanics of those parentheses?
It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:
http://en.wikipedia.org/wiki/Closure_%28computer_science%29
http://peter.michaux.ca/articles/javascript-namespacing
Andy Hume pretty much gave the answer, I just want to add a few more details.
With this construct you are creating an anonymous function with its own evaluation environment or closure, and then you immediately evaluate it. The nice thing about this is that you can access the variables declared before the anonymous function, and you can use local variables inside this function without accidentally overwriting an existing variable.
The use of the var keyword is very important, because in JavaScript every variable is global by default, but with the keyword you create a new, lexically scoped variable, that is, it is visible by the code between the two braces. In your example, you are essentially creating short aliases to the objects in the YUI library, but it has more powerful uses.
I don't want to leave you without a code example, so I'll put here a simple example to illustrate a closure:
var add_gen = function(n) {
return function(x) {
return n + x;
};
};
var add2 = add_gen(2);
add2(3); // result is 5
What is going on here? In the function add_gen you are creating an another function which will simply add the number n to its argument. The trick is that in the variables defined in the function parameter list act as lexically scoped variables, like the ones defined with var.
The returned function is defined between the braces of the add_gen function so it will have access to the value of n even after add_gen function has finished executing, that is why you will get 5 when executing the last line of the example.
With the help of function parameters being lexically scoped, you can work around the "problems" arising from using loop variables in anonymous functions. Take a simple example:
for(var i=0; i<5; i++) {
setTimeout(function(){alert(i)}, 10);
}
The "expected" result could be the numbers from zero to four, but you get four instances of fives instead. This happens because the anonymous function in setTimeout and the for loop are using the very same i variable, so by the time the functions get evaluated, i will be 5.
You can get the naively expected result by using the technique in your question and the fact, that function parameters are lexically scoped. (I've used this approach in an other answer)
for(var i=0; i<5; i++) {
setTimeout(
(function(j) {
return function(){alert(j)};
})(i), 10);
}
With the immediate evaluation of the outer function you are creating a completely independent variable named j in each iteration, and the current value of i will be copied in to this variable, so you will get the result what was naively expected from the first try.
I suggest you to try to understand the excellent tutorial at http://ejohn.org/apps/learn/ to understand closures better, that is where I learnt very-very much.
...but what about the previous round parenteses surrounding all the function declaration?
Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:
function() {
alert('hello');
}();
You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:
function doSomething() {
}
...and you can't have a function statement without a function name.
function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!
Juts to follow up on what Andy Hume and others have said:
The '()' surrounding the anonymous function is the 'grouping operator' as defined in section 11.1.6 of the ECMA spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.
Taken verbatim from the docs:
11.1.6 The Grouping Operator
The production PrimaryExpression : ( Expression ) is evaluated as follows:
Return the result of evaluating Expression. This may be of type Reference.
In this context the function is treated as an expression.
A few considerations on the subject:
The parenthesis:
The browser (engine/parser) associates the keyword function with
[optional name]([optional parameters]){...code...}
So in an expression like function(){}() the last parenthesis makes no sense.
Now think at
name=function(){} ; name() !?
Yes, the first pair of parenthesis force the anonymous function to turn into a variable (stored expression) and the second launches evaluation/execution, so ( function(){} )() makes sense.
The utility: ?
For executing some code on load and isolate the used variables from the rest of the page especially when name conflicts are possible;
Replace eval("string") with
(new Function("string"))()
Wrap long code for " =?: " operator like:
result = exp_to_test ? (function(){... long_code ...})() : (function(){...})();
The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.
As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P
See this question. The first set of parenthesis aren't necessary if you use a function name, but a nameless function requires this construct and the parenthesis serve for coders to realize that they've viewing a self-invoking function when browsing the code (see one blogger's best-practices recommendation).