Ticket #8547 (closed bug: wontfix)
$.each behaviour with null object
| Reported by: | theaspect@… | Owned by: | |
|---|---|---|---|
| Priority: | undecided | Milestone: | 1.next |
| Component: | core | Version: | 1.5.1 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
Hi guys? i've posted it on forum, but nobody care, copy bug here why behaviour of
$.each(null,function(){alert(1)})
differs from
for(a in null){alert(1)}
jquery raises exception
TypeError: object is null
So
each: function( object, callback, args ) {
var name, i = 0,
length = object.length, <<-HERE COMES PROBLEM
isObj = length === undefined || jQuery.isFunction(object);
we should test is object is null
Change History
comment:2 Changed 2 years ago by theaspect@…
@boushley you want me to post the patch?
each: function( object, callback, args ) {
+ if (object == null) return null;
var name, i = 0,
comment:3 Changed 2 years ago by dmethvin
If the code can't help itself but pass null/undefined then just guard against it with $.each(obj||[],function(){alert(1)}) and all is well. That way we don't mask problems and devs can either explicitly say they don't mind null (as above) or figure out why they are getting it in the first place.
comment:4 follow-up: ↓ 5 Changed 2 years ago by theaspect@…
same for underscore.js
works without exceptions:
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
...
comment:5 in reply to: ↑ 4 Changed 2 years ago by theaspect@…
Replying to theaspect@…:
i've tested and same behavior in Dojo, ExtJS, Mootools
your antispam system sux
same for underscore.js
works without exceptions:
var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; ...
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

For in is meant for iterating over members of an object, $.each is meant to iterate over items of an array, so I'm not sure why the comparison is valid. Sure you can use a for in to iterate over an array, but that's because of the way javascript represents arrays.
I don't think this is something we should really be concerned with. Would you propose a null check and then immediately return if it is null? I think this fits under garbage in garbage out.