My first Javascript program

Embarrassingly for a techie, my coding skills are somewhat lacking – despite various dabblings, my focus largely having been system administration without a firm basis in basic programming logic. :(

Clearly, if this is something I’m wanting taught in schools, I should make an effort to learn and understand about it myself however there are plenty of bits of code that I aspire to make small modifications to, yet lack the knowledge to do so.

Codecademy‘s high profile launch of CodeYear, provided the perfect, gentle opportunity, to quickly get to grips with some really basic concepts without feeling patronised or rushed or guilty of wasting someone’s time.

I’ve just completed the Codecademy week 1 courses, and my biggest success so far is putting together this simple Javascript FizzBuzz game program. Not a ground breaking achievement, but considering this is (apparently) a frequently used interview task, it certainly feels like something has been accomplished!

Onwards!

Javascript (execute in Firebug debugger)

// What number shall we play up to?
var number = 100

// for the numbers 1 through 20,
for (i=1; i<=number; i++) {

// if the number is divisble by 3 and 5, write "FizzBuzz"
if ( i % 3 === 0 && i % 5 === 0 ) {
console.log("FizzBuzz");
}

// if the number is divisible by 3, write "Fizz"
else if ( i % 3 === 0 ) {
console.log("Fizz");
}

// if the number is divisible by 5, write "Buzz"
else if ( i % 5 === 0 ) {
console.log("Buzz");
}

// otherwise, write just the number
else {
console.log(i);
}
}

3 thoughts on “My first Javascript program

  1. > // What number shall we play up to?
    > var number = 100

    > // for the numbers 1 through 20,

    And here we have a valuable lesson: Never Trust The Comments :-)

  2. Treating ((i % 3 === 0) && (i % 5 === 0)) as a separate case feels ugly.

    // What number shall we play up to?
    var number = 100

    for (i = 1; i <= number; i++) { //loop through 1 – number
    var toPrint = "";

    if (i % 3 === 0) { //if divisible by 3
    toPrint += "Fizz";
    }

    if (i % 5 === 0) { //if divisible by 5
    toPrint += "Buzz";
    }

    if (toPrint === "") { //if we haven't written anything special for the number
    console.log(i); //then just print the number
    } else { //otherwise print our special word
    console.log(toPrint);
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>