JavaScript Debugging ProTip
Do you ever wonder why your app isn't doing what it's supposed to?
I do, but only ALL.THE.TIME...
I have found it's often a "handshake failure," when some item of data being OVER HERE is passed so it can be used OVER THERE and something gets lost, overwritten, marked as the wrong data type, etc.
So, of course we use lots of "print" or "console.log" statements to log the data so we can compare what IS there with what we EXPECT to be there.
If you do this enough, you end up with a bunch of statements that say "userId: 12345" ALL OVER THE PLACE, and it can be hard to tell. To counter this, I would add in some notes about where the log was being written, so instead I would see "in userClient, userId: 12345"
This makes it a lot clearer, but when I want to see the output of a whole object, string concatenation just doesn't work, I get "in userClient, user: [object Object]." Not helpful.
Today I learned about console.log with commas!
(OK, I learned about it AGAIN, I've actually learned this several times and keep forgetting, grr. That is why I'm writing a post now, so I can reference it easily).
Next time this happens to you, try this:
console.log("in userClient, user: ", user);
Instead of [object Object], you'll get this:
in userClient, user: {name: "dave", hair: "none"}
This will make it much clearer, so you can see what the values are at given lines in your code, and identify the point (or points, yes, it's often plural) of failure so you can fix them.
For bonus points, you can even use color in your console log statements, even different colors for different classes (red for service, blue for client, etc), like this:
console.log("%cin userClient, user: ", "color:red; font-size:20px", user )
That will give you the following output:
So, I hope that helps you become the best bug-hunter in the universe. If you use this to good effect, I'd love to hear about it in the comments. (If no one comments, I'm going to have to misspell something, that always brings out the commenters...)
If you haven’t tried it yet, console.table() is going to blow your mind.