JavaScript exercises

Good coding starts with getting the basics right! These cleanly-coded JavaScript functions written for my Coder Foundry class perform some basic and not-so-basic tasks. Click the "View Code" button to see exactly how each one is written.

Factorial view code

Task: Write a function that calculates the factorial of a number. The factorial of a non-negative interger n, denoted by n!, is the product of all positive integers less than or equal to n. (i.e. 5! = 5 x 4 x 3 x 2 x 1 = 120)

Palindrome view code

Task: Define a function palindrome() that computes the reversal of a string, returning true if the string is a palindrome (the same forwards and backwards), and false otherwise.

FizzBuzz view code

Task: Write a program that iterates the integers from 1 to 100, printing the numbers to the screen. For each number that is a multiple of 3, however, print "Fizz" instead of the number. For multiples of 5 print "Buzz" instead of the number. For numbers that are multiples of both print "FizzBuzz."

Perfect Numbers view code

Task: Write one function that determines whether a given number is "perfect" and a second function to display all perfect numbers between 1 and 10,000. In number theory a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself. The first perfect number is 6 - it's positive divisors (excluding itself) are 1, 2, and 3, whose sum is 6.

Happy Numbers view code

Task: Write a program to display the first 5 happy numbers. Happy numbers are numbers that can be reduced to 1 through the following process - Start with any positive integer, replace the number with the sum of the squares of its digits, and repeat until the result is 1 or the result is an endless loop.

Armstrong Numbers view code

Task: Write a program to find all three-digit Armstrong numbers. An Armstrong number is an integer such that the sum of the cubes of its digits is equal to the number itself (i.e. 371 is an Armstrong number since 33 + 13 + 13 = 371).

Max of Three view code

Task: Define a function that takes 3 numbers as arguments and returns the largest of them.

Sum view code

Task: Define a function sum() that sums all the all the numbers in an array of numbers.

Multiply view code

Task: Define a function that calculates the product of all the numbers in an array of numbers.