5

I have been searching, but no clues... or I haven't search the proper way (so please excuse me if duplicate)

Does the following code, mean: If there is no jQuery defined, or no document ready?

!function ($) { 

///

!function ($) { $(function(){ // I know this is an alias to $(document).ready() ..... }(window.jQuery) // Ending of !function 

I'm asking, because I saw it here: http://twitter.github.io/bootstrap/assets/js/application.js and have no I really don't know what it means.

4
  • 3
    Here is what the ! is for: stackoverflow.com/questions/3755606/… Commented Jun 25, 2013 at 19:21
  • 1
    oh I see. It is a pity I couldn't find that answer before. I got no results by searching !function ($) { Commented Jun 25, 2013 at 19:23
  • 1
    Google is not very helpful when you search for characters like ! :) Commented Jun 25, 2013 at 19:24
  • I tried escaping it in different ways, still no success... huh, google Commented Jun 25, 2013 at 19:25

2 Answers 2

5

In this case, ! is being used because it's an operator, so the rest of the line will be treated as an expression rather than a statement. This is a way of writing an immediately invoked function expression. The more common idioms can be found here:

Javascript immediately invoked function patterns

Sign up to request clarification or add additional context in comments.

Comments

3

! on a function(){}() simply flips (or negates) the value that's returned after immediately calling the function that's defined. Notice that immediately after the function definition, at the very last line, it says (window.jQuery) — that's passing jQuery as the argument to the function and calling it immediately.

But in this case it doesn't appear to do anything important since the return value won't be used anyway. The function will still be executed though.

Also, it says this at the top of the file:

// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ 

So that's evidence further that it's not meant to serve any real purpose.

6 Comments

I'm sorry, but it is not what I have asked.
@w0rldart: I realized. I've actually answered the question now - go ahead and refresh.
thank you for having in consideration my question, and actually giving me an answer :)
so then, in my case !function ($) { wouldn't have any use... as I already have jQuery included and executing on document.ready, right?
The ! doesn't seem to have a purpose, but this isn't about document.ready - this is about scoping the $ variable to prevent conflicts between jQuery and other libraries that happen to use $.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.