Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can someone experienced give my JS a look?

I've been working on a project today in which I have a program that will show knitting charts that can be cycled through and they're stored in 2d arrays.

The thing I'm worried most about is whether or not my code is commented well and readable. Here's a link to the github repo that I'm working on the project in. I'd appreciate any help that anyone can give!

https://github.com/fourmatsee/knittingchartproject

P.S. I know that it's not recommended to do all of the styling and content creation through JS but I had to do the element creation there, and without JS the webapp wouldn't work for its goal anyway, so I didn't see that as a problem much, while it allows it to be a lot more responsive.

1 Answer

One piece of advice... cache your selectors!

Instead of:

$('#last').empty();
if(last[0] === "empty") {
  $('#last').addClass("empty");
} else {
  if ($('#last').hasClass('empty')) $('#last').removeClass('empty');
}
for (var i = 0; i < countLast; i++) {
  $('#last').addP(last[i]);
}

use something like the following:

var lastItem = $('#last');

lastItem.empty();
if(last[0] === "empty") {
  lastItem.addClass("empty");
} else {
  if (lastItem.hasClass('empty')) lastItem.removeClass('empty');
}
for (var i = 0; i < countLast; i++) {
  lastItem.addP(last[i]);
}

This means that your code only accesses the DOM once and then refers to a variable in every other instance. Making your code that much faster.

Thanks! That'll be my goal for the day. I appreciate the look!