Organazing jQuery/JS Code

Hey guys and gals,

So I disappeared for a few weeks because I’ve been learning ASP.NET MVC, data modeling, databases, and other back-end stuff… But I’m back doing some front-end now and I’m still far, far, more experienced with C# than I am with jQuery/JS. I’ve just started using some jQuery to pull some JSON from my website’s API… I’m now learning and tooling around with client-side programming so as to make my websites faster and use less server-side resources. Having said this, I’m finding my jQuery to be UUUUUUGGGGGGLLLLLLYYYYYYYY compared to my C#. Like for some reason my Visual Studio kind of turns it into a garbled mess, at least compared to what it does with my C#. I’m not sure if it always looks like this and it’s just me not being used to it yet, but even though I wrote the code myself and know what it is doing, the way it is formatted confuses the heck out of me when I look at it and I feel like way down the line, I could misunderstand it looking like this.

Again, maybe this is just how jQuery looks and since I’m a noob, I just need to get more used to it. One last thing I was thinking is maybe it has to do with my Visual Studio’s syntax highlighting… Maybe it supports C# better than jQuery??? But check it out and let me know what you think:

Ugly jQuery:

Pretty C#:

I’m not sure what you’re viewing as ‘ugly’ in the jQuery - is it just the syntax highlighting, or something else?

I don’t know that editor at all, but if it is just syntax highlighting, are there plug ins or themes that can change that for you?

I’m not sure if this is what you mean but I think your problem is with the callback hell. There is even a website dedicated to the issue: http://callbackhell.com

3 Likes

Yup. That’s pretty much it. I was just referring to how the code is all stacked like some kind of staircase like that lol. Thanks for that link, very informative!

One way to tackle callback hell, without resorting to extra tooling like promisifying things or what have you, is to write your code more declaratively.

That is to say, you could define your functions elsewhere in the code, one by one, or even in a different file, and then, where you write your main jQuery logic in your example above, you’d just insert the function names to call them, rather than writing them out in-line.

It seems trivial at first, but the positive effect it has on readability is surprisingly powerful!

5 Likes

Pyramid of Doom