JS · Lesson 5

Functions

Reusable blocks of code that take inputs and give answers

When you need the same steps in many places, you don't have to copy them. Put them in a function once, give it a name, and call that name whenever you need it.

What you'll learn

  • How to put code in a function and run it whenever you need it.
  • How to give a function inputs with parameters.
  • How to get an answer back with return.

Welcome to functions

A function is a named block of code. Writing it is called declaring it, and running it is called calling it. You've already called functions made by others: console.log( ) and document.getElementById( ). Now you'll make your own.

A function can take inputs, do its job, and give back an output.

Think of a blender at a fruit shake stand. You put in fruit (the input), press the button (call the function), and a shake comes out (the output). The blender works the same way every time, whether you put in mango or banana. You don't need to know how its blades turn. You only need its name and what to put in.

The input goes in through the parentheses, and return sends the output back.

A closer look

How a function is written

Function names follow the same rules as variable names. A name that starts with a verb, like addPrices or showGreeting, tells you what the function does.

Parameters and arguments

Parameters are the names in the declaration, like a and b. Arguments are the real values you pass when you call it, like 25 and 40. They match up in order, so inside the function, a is 25 and b is 40.

return: the answer

return sends a value back to the line that called the function. You can keep it in a variable, log it, or use it in a sentence. return also ends the function right away, so any lines after it inside the function don't run.

Why use functions?

Functions save you from writing the same code twice. When something needs to change, you fix it in one place. They also make code easier to read: a line like showGreeting("Ana") says what it does. In JS Lesson 8, you'll use functions to react to clicks and typing.

Let's build it

Let's write a few small functions for Front Page Bytes. The HTML and CSS stay the same in every step: a heading and two boxes, #greeting and #total. The first steps write to the console, and the last step changes the page.

Step 1: Declare a function and call it

Your code
function sayHello() {  console.log("Hello, reader!");} sayHello();sayHello();
What you see

Console

    Nothing here yet. console.log() writes here.

    Lines 1 to 3 declare sayHello. Nothing happens yet. Lines 5 and 6 call it, and each call runs the code inside, so the console shows Hello, reader! twice.

    Step 2: Give it an input

    Your code
    function sayHello(name) {  console.log("Hello, " + name + "!");} sayHello("Ana");sayHello("Ben");
    What you see

    Console

      Nothing here yet. console.log() writes here.

      name is a parameter. The first call passes "Ana", so inside the function name is "Ana". The second call passes "Ben". One function, two different messages.

      Step 3: Get an answer back with return

      Your code
      function addPrices(a, b) {  return a + b;} const total = addPrices(25, 40);console.log(total);console.log(addPrices(100, 50));
      What you see

      Console

        Nothing here yet. console.log() writes here.

        return a + b; sends the sum back. addPrices(25, 40) becomes 65, which goes into total. Line 7 uses the answer directly inside console.log: 150.

        Step 4: return stops the function

        Your code
        function checkAge(age) {  if (age < 13) {    return "Please ask a parent first.";  }  return "Welcome!";} console.log(checkAge(10));console.log(checkAge(15));
        What you see

        Console

          Nothing here yet. console.log() writes here.

          For age 10, the if is true, so the function returns Please ask a parent first. and stops. Line 5 never runs. For age 15, the if is false, so the function goes on to line 5 and returns Welcome!

          Step 5: Use functions on the page

          Your code
          function addPrices(a, b) {  return a + b;} function showGreeting(name) {  document.getElementById("greeting").innerHTML = "Good morning, " + name + "!";} showGreeting("Ana");document.getElementById("total").innerHTML = "Total: " + addPrices(25, 40) + " pesos";
          What you see

          Console

            Nothing here yet. console.log() writes here.

            showGreeting doesn't return anything. Its job is to change the page. addPrices returns a number, which the last line puts inside a sentence. Both boxes now show the results: Good morning, Ana! and Total: 65 pesos.

            Quick notes

            function Declare and call
            function sayHello() { console.log("Hi!"); }

            How to use

            • function name() { } Declares a function: a name for a block of code.
            • name(); Calls it: runs the code inside. The () are needed.
            • Declaring a function doesn't run it. Only calling it does.

            Examples

            1. A message you show many times.

              function welcome() {  console.log("Welcome to the class!");}welcome();
            2. Clear a box on the page.

              function clearBox() {  document.getElementById("box").innerHTML = "";}
            ( ) Parameters and arguments
            function sayHello(name) { } sayHello("Ana");

            How to use

            • function name(a, b) { } a and b are parameters: names for the inputs.
            • name(5, 10); 5 and 10 are arguments: the values you pass in.
            • They match up in order: a gets 5, b gets 10.

            Examples

            1. Greet anyone by name.

              function greet(name) {  console.log("Hi, " + name);}greet("Ana");
            2. Two inputs.

              function introduce(name, age) {  console.log(name + " is " + age);}introduce("Ben", 12);
            return Send an answer back
            return a + b;

            How to use

            • return value; Sends a value back to where the function was called.
            • return also stops the function. Lines after it don't run.
            • Without return, a function gives back undefined.

            Examples

            1. Double a number.

              function double(n) {  return n * 2;}console.log(double(21));
            2. Area of a rectangle.

              function area(width, height) {  return width * height;}const room = area(4, 5);
            3. Return early.

              function grade(score) {  if (score >= 75) {    return "Passed";  }  return "Try again";}

            Common mistakes

            These are mistakes many beginners make. None of them shows an error, so the console is your best clue.

            Forgetting the ( ) when calling

            The mistake
            function sayHello() {  console.log("Hello, reader!");} sayHello;console.log(sayHello);
            What you see

            Console

              Nothing here yet. console.log() writes here.

              sayHello; only names the function. It doesn't run it, so Hello, reader! never shows. Logging it without ( ) shows the function itself, not its result.

              Tip: Call a function with parentheses: sayHello(); even when it takes no inputs.

              Forgetting return

              The mistake
              function addPrices(a, b) {  a + b;} console.log(addPrices(25, 40));
              What you see

              Console

                Nothing here yet. console.log() writes here.

                The function works out a + b, but then throws the answer away. Without return, it gives back undefined, and that's what the console shows.

                Tip: Write return in front of the answer: return a + b;

                Passing numbers as text

                The mistake
                function addPrices(a, b) {  return a + b;} console.log(addPrices("25", "40"));
                What you see

                Console

                  Nothing here yet. console.log() writes here.

                  "25" and "40" have quotes, so they are strings. For strings, + joins instead of adding, and the answer is 2540 instead of 65.

                  Tip: Pass numbers without quotes: addPrices(25, 40).

                  Test your knowledge

                  Write JavaScript in the JS tab. Make a function that works out a bill, like the price of some banana cues and turon, then show the answer on the page.

                  No clicking needed. Each goal gets a check mark by itself once your code does it.

                  1. Declare a function with the function keyword. not done yet
                  2. Give your function at least one parameter. not done yet
                  3. Send an answer back with return. not done yet
                  4. Call your function and show its answer in #bill. not done yet
                  Your code
                  What you see

                  Console

                    Nothing here yet. console.log() writes here.

                    Try an exercise

                    Recap

                    • function name() { } declares a function, and name(); calls it. Declaring alone doesn't run the code.
                    • Parameters are the names for a function's inputs. Arguments are the values you pass in, matched in order.
                    • return sends an answer back and ends the function. Without it, the function gives back undefined.

                    References

                    Lesson content prepared by the WebCore F.E. team for beginner learners. The following references were used in preparing this lesson.

                    • ECMA International. ECMAScript Language Specification (official specification). Open reference