Eloquent Javascript: Exercises

/
3

Looping a triangle

Write a loop that makes seven calls to console.log to output the following triangle:

#
##
##
###
####
####
#####
    let i = 0;
while (i++ < 7) console.log("#".repeat(i));

FizzBuzz

Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead. When you have that working, modify your program to print "FizzBuzz" for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those).

let i = 1
do {
    divBy3 = i % 3 === 0
    divBy5 = i % 5 === 0
    switch (true) {
        case (divBy3 && divBy5):
            console.log('FizzBuzz')
            break
        case (divBy3):
            console.log('Fizz')
            break
        case (divBy5):
            console.log('Buzz')
            break
        default:
            console.log(i)
    }
} while (i++ <= 100)

Chessboard

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a "#" character. The characters should form a chessboard. Passing this string to console.log should show something like this:

 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #

When you have a program that generates this pattern, define a binding size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

const drawBoard = function (size) {
    let row = 0
    let str = ''
    while (row++ < size) {
        let col = 0
        let offset = row % 2
        while (col++ < size) {
            str += ((col + offset) % 2) == 0 ? " " : "#"
        }
        str += "\n"
    }
    console.log(str)
}
drawBoard(8)