John Lekberg


JUNTO Practice - "Eloquent JavaScript, Chapter 2"

Discussed on 2019-11-07.

Eloquent Javascript

Chapter 2 exercises:


Solution - Daniel

Looping a Triangle

for (var x = "#"; x.length <= 7; x += "#") 
  console.log(x);

FizzBuzz

for (var i=1; i <= 100; i++)
{
    if (i % 3 == 0)
        console.log("Fizz");
    else if (i % 5 == 0)
        console.log("Buzz");
    else
        console.log(i);
}

Chessboard

var b = "";
var total = 8;

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

console.log(b);  

The FizzBuzz solution is incorrect. For i = 15, that code will print out Fizz, when it should print out FizzBuzz.

-- John


Solution - John

Looping a Triangle:

for (let n = 1; n <= 7; n++) {
	console.log("#".repeat(n));
}

FizzBuzz:

const fizz = (n) => n % 3 ? "" : "Fizz";
const buzz = (n) => n % 5 ? "" : "Buzz";
for (let n = 1; n <= 100; n++) {
	console.log((fizz(n) + buzz(n)) || n); 
}

Chessboard:

const size = 8;
for (let r = 0; r < size; r++) {
	let row = "";
	for (let c = 0; c < size; c++) {
		row += " #"[(r + c) % 2];
	}
	console.log(row);
}