JQuery hides simple JavaScript errors

I use jQuery and fleet in chrome and firefox. When I work on my code, I find that execution without the slightest glitch fails with regard to such stupid things as access to non-existent hash structures, etc.

There seems to be some try {} catch {} logic in jQuery that is stopping me from seeing any errors.

Any pointers on how to get around this without using hack-n-slash to isolate where the simple error is?

jshint is not very useful.

- edit -

more debugging shows the trend.

Basically I find typos (undefined variables) and premature selection of object properties before they exist. Using .hasOwnProperty () helped, but was cumbersome. I think I saw a handy utility somewhere to briefly work through deep structures.

+5
source share
2 answers

.lengthis your friend when debugging jQuery. Because even if:

document.getElementById('nonexistent');

will return nullin JavaScript, using the jQuery selector will return an object and produce true:

if(!document.getElementById('nonexistent')) {
    alert('not here!');
}

if(!$('#nonexistent')) {
    alert('here, here!');
}

It means that:

$('#nonexistent').doSomething().doSomethingElse().whatever();

Probably not throwing errors, so it will be difficult for you to find out what is “not working” in the chain.

However, checking the length of an object works:

if(!$('#nonexistent').length) {
    alert('not here!');
}

jQuery is designed to be silent, as one of its main uses is chaining. And if prototype selectors or methods return null or false in the chain, using jQuery will generate null-referenced errors more often than most inexperienced programmers want.

, , , , . :

var debug = ['hide','show'], // Array of jQuery methods to debug
    i = 0, name;

for(; debug[i]; i++) {
    name = debug[i];
    if (typeof $.fn[name] == 'function') {
        $.fn[name] = (function(name, fn) {
            return function() {
                if ( !this.length ) {
                    console.warn('No elements selected when calling '+name);
                }
                fn.apply(this, Array.prototype.slice.call( arguments ));
            };
        }(name, $.fn[name]));
    }
}

, 'hide', , :

$('#nonexistent').hide();  // consoles a warning

Fiddle: http://jsfiddle.net/B4XQx/

+3
0

All Articles