Yes, there are some gotchas. The biggest one is that console.log(someObject)
will print something that is a reference to that object, so if the value of the object changes it's possible the console.log
might show the newer state of the object rather than the object at the moment you wanted.
I personally get around this by making a deep copy of any object I log out. That way I know the state of the object being logged is the state of the object when I logged it. By far the easiest way to make a deep copy of an object is:
var newObject = jQuery.extend(true, {}, oldObject);
So, for log statements just do:
console.log(jQuery.extend(true, {}, oldObject));
Or make it a function:
function deepCopy(oldObject) {
return jQuery.extend(true, {}, oldObject);
}
console.log(deepCopy(someObject));
There are also things like circular references to worry about.
Moreover, some browsers don't even have a console
to log to, so make sure to 1) never put debug code into production, and 2) shim the console.
Edit:
Per your comment, here is an example of how to handle async logging with jQuery:
Let's say you are getting lots of messages, and you want to log which message you are getting responses from. If you do this, you'll get confused real quick because the value of messsageId
in the function will be changing.
for(var i = 0; i < 10; ++i) {
getMessage(i);
}
function getMessage(messageId) {
$.ajax({
url: 'myScript',
success: function(data) { console.log('Got data for ' + messageId, data); }
});
}
// This will most likely give you 10 log statements all with id = 9.
To get around this problem, we can create a closure. Understanding closures is outside the scope of this thread, but basically it will trap the value at the function level:
for(var i = 0; i < 10; ++i) {
getMessage(i);
}
function onSuccess(messageId) {
return function(data) {
console.log('Got data for ' + messageId, data);
}
}
function getMessage(messageId) {
$.ajax({
url: 'myScript',
success: onSuccess(messageId);
});
}
// This will give 10 log statements each with the correct id