Function Smith — JavaScript

Create functions: 15 levels of parameters, return, arrow vs declaration and default values. A JavaScript functions game for mastering reusable code.

What you learn in this game

A function is a block of code that can be called repeatedly. A function can take parameters (input) and return a value with return.

The if...else statement lets code branch based on a condition. The % (modulo) operator returns the remainder of a division.

Strings have many built-in methods. .repeat(n) repeats a string n times. You can also use a loop to build the string manually.

To process each element of an array, you can use a for loop or a method like .reduce(). A for loop iterates one by one, .reduce() accumulates a value.

A default parameter lets a function have a fallback value if the parameter isn't given. It's written with = after the parameter name.

The .filter() method makes a new array of the elements that pass a condition. Its callback must return true (keep) or false (drop).

What the levels ask

  1. Create a function sapa that takes a nama parameter and returns the string "Halo, {nama}!".
  2. Create a function luasPersegi that takes a sisi parameter and returns the area of a square (sisi x sisi).
  3. Create a function genapGanjil that takes a number and returns "genap" or "ganjil".
  4. Create a function maks that takes two numbers and returns the bigger one.
  5. Create a function ulang that takes a string kata and a number n, then returns that word repeated n times (without spaces).
  6. Create a function jumlah that takes an array of numbers and returns their total sum.
  7. Create a function sapaPagi that takes nama (default: "Teman") and returns "Selamat pagi, {nama}!".
  8. Create a function fizzBuzz that takes a number. Return "Fizz" if it's divisible by 3, "Buzz" if divisible by 5, "FizzBuzz" if divisible by both, or the number itself (as a string).
  9. Create a function positifSaja that takes an array of numbers and returns a new array containing only the positive numbers (> 0).
  10. Create a function buatProfil that takes nama and umur, then returns the object { nama, umur, dewasa } where dewasa is true if umur >= 17.
  11. Create a function hitungKata that takes a sentence string and returns the number of words in it. Words are separated by spaces.
  12. Create a function pangkat (power) that takes base and exp (an integer >= 0) and returns base raised to the power exp. Use recursion (no ` or Math.pow`).

And more, 20 levels in all.