Lesson 4 Recap

In lesson 4 we learned more about functions. A function is a set of instructions that is grouped under one name.

Functions allow us to write code once and then use it over and over again, in many different places. It also allows us to put all the code to do one "thing" into one place. Because its much easier to think about a "thing" than it is to think about all the things that that "thing" does, you can write much clearer code using functions.

Imagine a video game that has enemies that move around trying to attack the player. If all the enemies are programmed to attack the same way, you wouldn't want to write the code that handles the attack logic for every single enemy. Instead, you would write a function to do it, and call the function on each of the enemies.

A function in Javascript

To declare a function in Javascript, you write the keyword function, followed by what you want to call the function. Following the name, you write an open parentheses, followed by any parameters for the function separated by commas, and then a close parentheses.

The body of the function follows this, denoted by open and closing curly braces. Everything in between the curly braces is considered the body, and every time the function is called, the body is executed.

This is what a function looks like:

function doJumpingJacks(count) {
   while(count > 0) {
      jump()
      raiseHands()
      spreadLegs()
      jump()
      lowerHands()
      closeLegs()
      count = count - 1
   }
}

A bit about naming

In Javascript, each name of a variable or function should be unique, so when you call the function, or access the variable, the computer knows what thing you are talking about. Many languages will complain if you name 2 or more functions or variables the same thing. In Javascript, however, if you name something the same as a previous thing, it just uses the new definition. So it is important to name your functions a good name, but also one that doesn't clash with something else.

One other note is that naming in Javascript is case sensitive. This means that the name hi is different from the name Hi, and refer to different things.

Parameters

Parameters to a function tell the function how to behave. If a function only does one thing, it may not have any parameters. In our code that we have been writing that is called when the button is pressed, no parameters were needed, because everything is determined by searching the document for things. But if we have a function that can do something differently based on specified instructions, we may end up writing less code.

In the doJumpingJacks example above, we accept a parameter count, which tells the function how many jumping jacks to do. If we had to write a function for every possible count of jumping jacks, that would be a lot of functions to write! By using a parameter, we only have to write one function.

Calling functions

We call a function by naming the function, followed by an open parentheses, then any values we want to pass to parameters separated by commas, followed by a close parentheses.

If you pass a parameter, this is called an argument to the function. Arguments are copied in MOST cases, which means you aren't changing any variables that are passed in. There are some cases where the arugments are changed, but I won't cover that today.

Each time you call the function, the function starts over, like it hadn't ever been called before. The parameters start out like variables, they can be changed inside the function just like you declared them with var.

Returning a result

At any time inside the function, you may return a result. A result is a single value, which can be anything a variable can hold. The code that called the function uses the return value as the value of the function call. Remember the call to document.getElementById(...)? It returns an HTML element object which we then could use to operate on parts of the HTML document.

You return with the keyword return, followed by the value you want to return.

An example of a function that returns would be something that adds 2 numbers together:

function addNumbers(num1, num2) {
   var result = num1 + num2
   return result
}

function func() {
   var x = addNumbers(1, 2)
   alert(x) // shows 3
}

The Complete example

In class, we moved the looping portion of our code into a reusable function that repeats text a given number of times.

Below is a complete example that you can copy and paste into a file, and then run on your browser, which shows what we accomplished in the class

<!DOCTYPE html>
<html>

<head>
    <title>Lesson 4 for coding!</title>
    <script>
        function repeatText(str, count) {
            var result = ""
            while(count > 0)
            {
                result = result + str
                count = count - 1
            }
            return result
        }

        function showString() {
            var isChecked = document.getElementById('doBold').checked
            var str = document.getElementById('thestring').value
            var target = document.getElementById('target')
            var count = parseInt(document.getElementById('repeat').value)

            var result = repeatText(str, count)
            if(isChecked)
            {
                target.innerHTML = '<b>' + result + '</b>'
            }
            else
            {
                target.innerHTML = result
            }
        }
    </script>
</head>

<body>
    Result appears here:
    <span id="target"></span>
    <p>
        <input id="thestring" placeholder="text">
        <input type="checkbox" id="doBold"> Bold
        <input type="number" id="repeat" value="1">
        <button type="button" onclick="showString()">Click Me</button>
    </p>
</body>

</html>

Playgrounds

As always, here are some playgrounds you can use. The JSFiddle playground links to a base project you can fork that includes the javascript console.

You can also open a local file (if you have a normal computer), name it anything with a .html extension, and then open it in your browser and it will work!

©2019 Steven Schveighoffer