! before function

Hi,
peeping into
http://twitter.github.com/bootstrap/javascript.html
code I’ve noticed this


!function ($) {
}(window.jQuery);

I don’t understand what’s the use of ! before function
Can you explain me, please ?

That preceeding “bang” will cast the result of the anonymous function as a boolean.

Then you can test for TRUE || FALSE on the execution of the anonymous function.

Thanks,
but in which case is it useful ?
Can you give me a practical example, please ?

Sure thing.

If something is being validated, and you need to display an error if it’s not validated, you could use the NOT operator like this:


var form = document.getElementById('orderInfo');
var isValid = validate(form);

if (!isValid) {
    // show an error message here
}

Sometimes it makes better sense to check things that way. If the NOT operator is not used, you can end up with a useless “do nothing” piece before you get to what actually needs to be done.


...
if (isValid) {
    // do nothing
} else {
    // show error
}

And sometimes, even if you do something when things are valid, it can make better sense to do the non-matching process first before going on to potentially more complex things for when it does match:


...
if (!isValid) {
    // show error
} else {
    // do lots of other things
}

Thanks Paul I just knew the NOT operator
but I don’t see the point using it like


!function ($) {
}(window.jQuery);

in bootstrap.js file
https://github.com/twitter/bootstrap/blob/master/docs/assets/js/bootstrap.js
there a list of !function and I don’t see why ?

Normally it is parenthesis that are used there instead, to create a function expression.


(function ($) {
}(window.jQuery));

I am not in favour of using ! instead of () though for shaving off just one character though, when it results in code that raises more questions.

I agree - the ! is just converting the presumably undefined value returned from the function to false and then applying the not to it to make it true and then discarding it. To me that sounds like more actual processing to be performed than simply wrapping the function inside (). After all the only requirement is that the word function have something in front of it in order to identify that you are defining an anonymous function so that JavaScript doesn’t give an error due to there not being a name for the function in the middle of the function(). Performing extra processing in order to make the source code one character shorter makes no sense.

[URL=“http://www.sitepoint.com/forums/”]
[URL=“http://www.sitepoint.com/forums/”]
[URL=“http://www.sitepoint.com/forums/”]