tags:

views:

46

answers:

3

Is there a better way to write this code? i tried function(){}(); but i got an error so i had to use DUMMY as a placeholder var. The function should run before alert b does. Whats a better way of writing this?

var DUMMY = function(){
    var names = "i dont want to be seen";
    alert('A');
}; DUMMY();

alert('B');
A: 
var DUMMY = function() { return; }; DUMMY();
jpabluz
No. You need the "()" after "DUMMY" to make the function call happen, and then you're left with exactly what the original question wants to replace.
Pointy
+3  A: 

You can use parentheses to make it look like an expression:

(function() { alert("hi"); })();

I recently saw this (at the TXJS conference):

!function() { alert("hi"); }();

The leading "!" serves the same purpose: the parser sees an expression instead of a function definition statement.

Pointy
Nice hack! In fact, you can use any unary operator. So maybe `void function() { alert("hi"); }()` is a little bit less confusing.
Gumbo
Well yes that works, but in all honesty that's the first time I've ever seen "void" used in Javascript, and I've been doing this for a while :-) Confusion is in the mind of the beholder!
Pointy
+1  A: 

I actually use the syntax you say doesn't work all the time. The thing is, you need to either store the return value, or make it an expression. So either:

var foo = function() { return false; }();

or

(function() { return false; }());

Note the difference between Pointy's answer on this one. The expression is the entire function (including the calling ()), not just the function declaration. Either way will do the same thing. Use what you feel is more readable (Personally I like this syntax better, but to each their own)...

ircmaxell