1

The return value of $(undefined) is an object or array or what?

The the body of $:

  return new jQuery.fn.init( selector, context, rootjQuery );

The particle body of jQuery.fn.init is:

  // HANDLE: $(""), $(null), $(undefined), $(false)
  if ( !selector ) {
          return this;
  }

My understanding is that:

 return new jQuery.fn.init( selector, context, rootjQuery );
            ~~~~~~~~~~
                ^
                |
               this?
yuan
  • 2,434
  • 1
  • 21
  • 29

3 Answers3

3

No. It's used with the new keyword, so the jQuery.fn. doesn't matter. What matters is its .prototype, which is jQuery.fn. See this question for the details.

So what's the return value of $(undefined)?

It's an empty object inheriting from jQuery's prototype, so it's the same as Object.create($.fn).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

The result is a jQuery object which does not contain any matched DOM elements; i.e. an "empty" jQuery object.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

$(undefined) will return a jQuery instance with "" selector.

Try it yourself with this code:

var output = '';
var jq = $(undefined);

for(var x in jq) {
    output += x + ' => "' + jq[x].toString() + '"' + "\n";
}

alert(output);

Sample output will be somewhat like this: http://pastebin.com/MwKYFM5w

  • No, the empty string is not really a selector - it would be handled like `undefined` :-) – Bergi Jul 02 '13 at 11:59
  • So will `$(undefined)` truncate `undefined` into `""` ? –  Jul 02 '13 at 12:00
  • They will both just be treated as "no selector" - the result is not even an empty collection (with `length` 0, `context` and `selector` properties) but an empty object without any properties. – Bergi Jul 02 '13 at 12:14