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

short code better than long code

I was doing some exercises online with js and you can see the solution if you want. and 9/10 is my code longer than the solution is this bad? And if I then have shorter code. It looks worse than the long solution code

//my code
for (let i = 1; i <= 100; i++) {
  if (i % 3 === 0 && i % 5 === 0){
    console.log('fizzbuzz');
  }if (i % 3 === 0){
    console.log('fizz');
  }else if (i % 5 === 0){
    console.log('buzz');
  }else {
    console.log(i);
  }
}
//solution
or (let n = 1; n <= 100; n++) {
  let output = "";
  if (n % 3 == 0) output += "Fizz";
  if (n % 5 == 0) output += "Buzz";
  console.log(output || n);
}
//my code
for (let i = 1; i <= 8; i++){
    if(i % 2 === 0){
        console.log(' # # # #');
    }else {
        console.log('# # # # ');
    }
}
//solution
let size = 8;

let board = "";

for (let y = 0; y < size; y++) {
  for (let x = 0; x < size; x++) {
    if ((x + y) % 2 == 0) {
      board += " ";
    } else {
      board += "#";
    }
  }
  board += "\n";
}

console.log(board);
Mike Hatch
Mike Hatch
14,940 Points

Are these the exercises from Eloquent JavaScript? Fizzbuzz and Chessboard from Chapter 2. If so, that is a very difficult book. I had to abandon it, but plan to come back to it later.

hey mike hatch

these are the exercises of chapter 2. But I can solve them but not in their way apparently. Does it make my code wrong then?

Mike Hatch
Mike Hatch
14,940 Points

Conor, I'd refer over to what Steven said to you in his Answer and reply there.

But I will say it again... you are going through a very difficult book. I wouldn't let it frustrate you. Those exercises weren't created by the author Marijn Haverbeke. And his answers aren't the only answers. Take a look at this: FizzBuzz: One Simple Interview Question.

1 Answer

Steven Parker
Steven Parker
231,072 Points

Shorter is only better when the code is equally easy to read and maintain.

An extreme example is the "minified" format often used for large frameworks and libraries to reduce loading time. You would certainly never want to permanently change the source to this format because it would be nearly impossible to read and maintain.