JavaScript 104: Monster Duel. An orange fire monster and a green monster fire energy at each other in an arena
Course image created with generative AI using OpenAI tools, with direction and curation by the course instructor.

CTEC 200 · Learn to Code by Hand · Primer 4 of 5

Functions

Eight short ideas about naming a piece of code, handing it values, and getting an answer back. Then you build Monster Duel, where the functions you write are the rules of the fight - and the strategy that wins it.

START HEREWhy functions

By now your code is getting long. A function lets you give a few lines a name, and then run them whenever you like by using that name. Write it once, use it a hundred times, fix it in one place.

You have already used plenty: console.log( ), show( ), block( ), push( ). Somebody wrote each of those. Now you write your own.

Same rules as before. Predict, run, change.

One thing to watch for this time: a function that does its sums but never hands back the answer. If you see undefined where you expected a number, look for a missing return.

CONCEPT 1A function is named code

Write function, a name, round brackets, and the code inside curly braces. That defines it. Then call it by writing its name and ( ), as often as you like.

Now change it: make the function print two lines instead of one. Notice that you only change it in one place, and both calls pick it up.

The same thing in C++
void greet() {        // void: this function gives nothing back
  cout << "Hello!";
}
greet();

CONCEPT 2Defining isn't running

JavaScript reads a function definition and keeps it for later. The code inside runs only when - and every time - something calls it.

Now change it: delete the last line and run it. Then put hello(); back as the very first line of the code. Does it still work?

CONCEPT 3Parameters: handing values in

The names inside the round brackets are parameters. They are variables that only exist inside the function, and they get their values from whatever is passed in when it is called.

Now change it: add a second parameter, times, and a loop that greets that many times. Call it with greet("Sam", 3).

CONCEPT 4return: handing an answer back

return sends a value back to wherever the function was called. The call then becomes that value - you can store it, print it, or do sums with it.

Now change it: write console.log(add(add(1, 2), 10)); and predict it before you run it.

CONCEPT 5Printing isn't returning

This is the commonest function bug. console.log shows a value to you. return hands it to the code. A function with no return gives back undefined.

Now fix it: change line 2 so that x really is 8.

CONCEPT 6Functions in loops, and functions calling functions

A function call can go anywhere a value can - including inside a loop, and inside another function. Small functions that each do one job, combined, is how big programs stay readable.

Now change it: write a function cube(n) that uses square inside it - return square(n) * n; - and loop that instead.

CONCEPT 7Scope: what happens in a function stays there

A variable made with let inside a function belongs to that function. It disappears when the function ends - even if it has the same name as one outside.

Now change it: remove the word let on line 3 and run it again. Then try printing a variable that only exists inside a function, from outside it.

CONCEPT 8Functions that answer yes or no

Many useful functions answer a question: "is this player alive?", "can they afford it?". They return true or false, so you can drop them straight into an if.

return also ends the function on the spot. Nothing after it runs.

Now shorten it: the whole body can be one line, return coins >= price;, because the comparison already is true or false. Try it.

THE BUILDMonster Duel

Your monster, Ember, fights Glitch. Glitch is tougher: more health, harder hits. Ember has one advantage - you write the rules. How much a hit does, what counts as alive, how healing works, when a critical lands, and the strategy that decides every move.

Until you write a rule, the arena uses a weak built-in one, so press Fight after every step and watch the battle change.

Same rules as before. Type it all by hand: paste is off. No AI.

RUN loads your functions. Fight plays a battle; Fight 100 times tells you how good your rules really are. CHECK CODE tests every step.

rules.js - your code
monster-duel.html
Ember
VS
Glitch
    Console