completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

Declaring & calling functions

Learn how JavaScript function declarations package reusable code, receive arguments through parameters, return values, and work with local and outer variables.

By the end you can
  • 01
    Write and call a functionWrite a function declaration, call it, and say when its steps run.
  • 02
    Pass values in and get one backTell parameters from arguments. Use return to give a value back, not just print it.
  • 03
    Know which names a function can useExplain local and outer variables and shadowing, and give functions clear names.

What a function is

A function is a group of steps with a name. You write the steps once. Then you can run them as many times as you like. Running a function is called calling it.

Without functions, you would copy the same five lines into ten places. With a function, you write those lines once and call the function ten times.

In the Thinking like a developer lesson, you split a problem into small jobs with names like addTip and splitBill. This lesson shows how to write those jobs in JavaScript. You will learn:

  • How to write a function and how to call it.
  • How to pass values into a function.
  • How to get a value back out with return.
  • Which variables a function can use.
Write a function, then call itPop out in the code editor (opens in a new tab)JavaScript
function greet(user) {
  return "Hello, " + user;
}

console.log(greet("Asha"));

Lines 1–3 write a function called greet. JavaScript does not run its steps yet. Line 5 calls greet with the value "Asha". The function gives back the text Hello, Asha, and line 5 prints it.

The call greet with Asha. A value card, Asha, goes into the function card greet(user). An arrow from the function gives back a new value card, Hello, Asha.greet("Asha")"Asha"goes ingreet(user)runs the steps"Hello, Asha"comes back
A call in three steps. The value "Asha" goes in. The function runs its steps. One new value, "Hello, Asha", comes back out.
The main idea

A function is a set of steps with a name. It can take values in. It can give one value back with return.

Real-life analogyA function is a recipe card

Writing a recipe card does not cook dinner. The card only keeps the steps for later. When you want food, you cook from the card. Writing a function is like writing the card. Calling the function is like cooking one dish from it.

In real life: The recipe's title
In JavaScript: The function's name, like makeGreeting
In real life: A blank on the card: “___ cups of flour”
In JavaScript: A parameter, written with the function
In real life: What you fill in today: “2 cups”
In JavaScript: An argument, given in one call
In real life: The finished dish
In JavaScript: The value the function gives back

Remember this: the steps inside a function do not run when JavaScript reads them. They wait. They run only when some code calls the function.

Function declarations

STEP THROUGH

The usual way to write a function is a function declaration. It has four parts, in this order:

  • The word function.
  • A name, like nameHere.
  • Round brackets (). They hold names for the values the function takes in. These names are called parameters. You'll meet them in the next section.
  • Curly braces { }. They hold the steps. These steps are called the function's body.
The parts of a function declarationPop out in the code editor (opens in a new tab)JavaScript
function nameHere(parameterHere) {  // steps go here  return valueHere;}

The name should say what the function does. The return line is optional. You'll learn what it does in the "Returning values" section.

The body waits for a callPop out in the code editor (opens in a new tab)JavaScript
function sayHi() {
  console.log("Hi");
}

console.log("Ready");
sayHi();

Lines 1–3 make the function sayHi. They don't print anything yet. Line 5 prints Ready. Line 6 calls sayHi, so now its body runs and prints Hi. That's why Ready comes first.

The replay below runs real code, one step at a time. First, guess what line 7 prints. Then press Step. Watch where it starts: it skips lines 1–4 and starts at line 6, the call.

Step through a function call
Step 0 of 6Ready
Your turn: follow the blue line

The function's steps wait until line 6 calls it. Pick a name and guess the greeting. Then step through the call and the return.

Running in
  1. script
Next: line 6
function makeGreeting(name) {  const message = "Hello, " + name + "!";  return message;} console.log(greeting);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the argument passed on line 6.

Pick a different name to start the replay again. The function stays the same.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Here is what happens, in order:

  1. Line 6 calls makeGreeting with a name.
  2. Inside the function, name gets that value.
  3. Line 2 builds the greeting and keeps it in message.
  4. Line 3 gives message back to line 6.
  5. Line 6 keeps that value in greeting.
  6. Line 7 prints greeting.
You can call a function before its line

You can call a function declaration on a line above the place where you wrote it. Before JavaScript runs the code in a file or a function, it first sets up every function declaration written there. This is called hoisting. The Hoisting & the temporal dead zone lesson explains the full rules later.

Call a function above its declarationPop out in the code editor (opens in a new tab)JavaScript
console.log(sayHi()); function sayHi() {  return "Hi before the declaration line";}

Line 1 calls sayHi before line 3 writes it. It still works, and it prints Hi before the declaration line.

Parameters and arguments

INTERACTIVE

A function can take values in. Two words describe this, and they are easy to mix up:

  • A parameter is a name in the round brackets of the declaration, like name in function greet(name). It is an empty spot that waits for a value.
  • An argument is the value you put in the round brackets of a call, like "Maya" in greet("Maya"). It fills that spot for this one call.

The table below sums this up. Read each row as: "this word means this, and you see it here."

Parameters and arguments compared
Word or ruleWhere you see itWhat it means
ParameterIn the declaration: function greet(name)A name that waits for a value. Each call fills it.
ArgumentIn the call: greet("Maya")The real value this one call gives the function.
Same number of eachtotal(price, tax) called as total(20, 3)The first argument goes to the first parameter, the second to the second, and so on.
A different numberA call with too few or too many valuesA parameter with no value gets undefined. This function ignores the extra values.
One value fills one parameterPop out in the code editor (opens in a new tab)JavaScript
function welcome(user) {
  return "Welcome, " + user;
}

console.log(welcome("Asha"));
console.log(welcome());

Line 5 calls welcome with the argument "Asha". So the parameter user gets "Asha", and the line prints Welcome, Asha.

Line 6 calls welcome with nothing in the brackets. So user gets undefined, the value JavaScript uses for "nothing here". The line prints Welcome, undefined.

Left: the call welcome with Asha puts the value Asha into the box user. Right: the call welcome with nothing in the brackets leaves the box user holding undefined.welcome("Asha")"Asha"userWelcome, Ashawelcome()undefineduserWelcome, undefined
The parameter user is like an empty box inside the function. Each call fills it. welcome("Asha") puts "Asha" in. welcome() passes nothing, so the box holds undefined.

Now try it yourself. The function below has two parameters, item and quantity. Each button picks a call with a different number of arguments: zero, one, two, or three. The right side shows the value each parameter gets.

Give a function 0 to 3 values
A function with two parametersPop out in the code editor (opens in a new tab)JavaScript
function describeOrder(item, quantity) {  return "item=" + item + ", quantity=" + quantity;} console.log(describeOrder());console.log(describeOrder("tea"));console.log(describeOrder("tea", 2));console.log(describeOrder("tea", 2, "ignored"));
This call0 arguments
  • item getsundefined
    quantity getsundefined
    the call gives backitem=undefined, quantity=undefined
Try it yourself

No arguments, so both parameters get undefined. undefined is the value JavaScript uses for “nothing was given”.

The same function, called with 0, 1, 2, or 3 arguments. A parameter with no argument gets undefined. An extra argument doesn't make a new parameter.

A parameter with no matching argument gets undefined. An extra argument is still passed to the function. But this function has no third parameter, so nothing uses the third value. The next lesson, Default & rest parameters, shows how to collect extra values on purpose. It also covers the older arguments object.

Parameter or argument?
  • name in function greet(name) {}
  • "Maya" in greet("Maya")
  • price and tax in function total(price, tax)
  • 20, 3 in total(20, 3)
  • quantity in function describeOrder(item, quantity)
  • The third value in describeOrder("tea", 2, true)
Try it yourself
0 of 6 correct

Is it a name in the declaration (a parameter) or a value in a call (an argument)? Sort each card.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Returning values

INTERACTIVE

return gives one value back to the code that called the function. That value is called the return value. As soon as return runs, the function stops.

Returning a value is not the same as printing it:

  • console.log shows a value on the screen. Your code can't use that shown value again.
  • return hands the value back to the call. Your code can keep it in a variable, add to it, or print it.

So a function that works out a number should usually return it. The code that called the function can then decide what to do with it.

Return a number, keep it, and use it againPop out in the code editor (opens in a new tab)JavaScript
function double(number) {
  return number * 2;
}

const score = double(3);
console.log(score + 1);

Line 5 calls double(3). Inside the function, line 2 returns 6. Line 5 keeps that 6 in score. Line 6 adds 1 and prints 7. If the function had only printed 6, line 6 would have no number to add to.

Left: console.log(6) shows 6 in the console window, and the code can't use it again. Right: return 6 hands 6 back, and it is kept in the box score.console.log(6)Console6shown, not keptreturn 66scorekept in score
console.log only shows a value on the screen. Your code can't use it again. return hands the value back to the call, so line 5 can keep it in score and use it later.

The playground below has three small functions. Pick a button to see what each one gives back.

Returning is not the same as printing
Print, return, and stop earlyPop out in the code editor (opens in a new tab)JavaScript
let checks = 0; function logTotal(price, tax) {  const total = price + tax;  console.log(total);} function returnTotal(price, tax) {  const total = price + tax;  return total;} function isAllowed(age) {  checks = checks + 1;  if (age < 18) return false;  checks = checks + 1;  return true;}
What happenedPrint only
  • the console showed23
    the call gives backundefined
Try it yourself

logTotal prints 23 on line 5. But it has no return, so the call gives back undefined. The printed 23 can't be used again.

Three small functions. With no return, the call gives back undefined. With return, the call gives back a value you can use. A return also stops the function.

The three cards below sum up what a call gives back.

No return

The call gives back undefined. This is true even if the function printed something while it ran.

A return value

The call gives back the returned value. Other code can keep it and use it.

An early return

A return inside an if can stop the function before its later lines run.

You have seen undefined in earlier lessons. It means "no value here". A function that never reaches a return gives back undefined too.

Local & outer variables

STEP THROUGH

A function can use two kinds of variables:

  • A local variable is made inside the function. Its parameters are local too. Only code inside the function can use them. Each call gets a fresh set.
  • An outer variable is made outside the function, in the code around it. The function can read it and change it.
Return a local valuePop out in the code editor (opens in a new tab)JavaScript
function makeLabel() {
  const label = "Save";
  return label;
}

console.log(makeLabel());

Line 2 makes a local variable, label. Only code inside makeLabel can use it. Line 3 returns its value. So line 6 gets the text and prints Save.

This is a good pattern to copy: values go in through parameters, and one value comes out through return.

Real-life analogyThe cook's counter and the shared pantry

A cook works with bowls on their own counter. Nobody else uses those bowls. The cook can also take things from the shared pantry. Now say the cook labels one bowl "pantry". When the cook says "pantry", they now mean the bowl, not the shelves.

In real life: Bowls on the cook's own counter
In JavaScript: Local variables inside one call
In real life: The shared pantry shelves
In JavaScript: Outer variables that nearby code can use
In real life: A bowl on the counter labelled “pantry”
In JavaScript: A local name that hides an outer name
In real life: Taking sugar from the shared jar
In JavaScript: Changing an outer variable

The next replay has both kinds of variables. It also shows shadowing: a local variable with the same name as an outer one. Inside its area, the local one hides the outer one.

Look at lines 6–10. They sit inside an extra pair of curly braces, called a block. Line 7 makes a new pantry that lives only inside that block. Line 5 runs before the block, so it still sees the outer pantry.

Local variables, outer variables, and a hidden name
Step 0 of 11Ready
Your turn: follow the blue line

Step through local variables, outer variables, and a local name that hides an outer one. This replays the example code one step at a time. It is not the browser's debugger.

Running in
  1. script
Next: line 1
let scoops = 0; function bake(label) {  const localBowl = label + " uses " + pantry;  {    let pantry = "cocoa";    scoops = scoops + 1;    return localBowl + "; local pantry is " + pantry;  }} const result = bake("cake");console.log(result);console.log(scoops);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

The table below lists each kind of name in that replay. Read each row as: "this kind of name, for example this one, works like this."

Local, outer, and hidden names in the bake example
Kind of nameExampleWhat to remember
Localconst localBowl inside bakeIt is made for this call. Code outside the function can't use it.
Parameterlabel in function bake(label)It is local too. It gets the argument of this call.
Outerlet scoops = 0 above the functionThe function can read it and change it.
ShadowingA local pantry while an outer pantry existsInside its block, the local pantry hides the outer one. The outer one doesn't change.

The next code tries to use a local variable from outside its function. It fails on purpose.

A local variable can't be used outsidePop out in the code editor (opens in a new tab)JavaScript
function wrapGift() {  const ribbon = "blue";  return ribbon;} wrapGift();console.log(ribbon);

Line 2 makes the local ribbon inside wrapGift. Line 7 is outside the function, and there is no ribbon out there. So line 7 throws a ReferenceError, the error JavaScript gives when it can't find a name. If outside code needs the value, return it.

Left: inside the function wrapGift, the box ribbon holds blue. Right: outside the function, console.log(ribbon) finds no box called ribbon, and the console shows ReferenceError.inside wrapGift"blue"ribbonribbon worksoutside, line 7ConsoleReferenceErrorconsole.log(ribbon)
ribbon is made inside wrapGift, so only code inside the function can use it. Outside, there is no box called ribbon, so line 7 throws a ReferenceError.
Local or outer?
  • label in function bake(label)
  • const localBowl, made inside bake
  • scoops, made above function bake
  • The first pantry, made above the function
  • let pantry = "cocoa" inside bake
  • result, made below the call to bake
Try it yourself
0 of 6 correct

Each card names a variable from the bake example. Is it local to bake, or outer? Sort each card.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Naming functions

STYLE

A function does something, so its name usually starts with a verb, a doing word like format, calculate, or get. You met this habit in the Coding style & naming lesson. It matters most for functions. With a good name, a reader knows what a call does without reading the function's body.

Names that say what the function doesPop out in the code editor (opens in a new tab)JavaScript
function formatPrice(price) {
  return "$" + price;
}

function isFree(price) {
  return price === 0;
}

console.log(formatPrice(3));
console.log(isFree(3));

formatPrice says it turns a price into text to show. isFree reads like a yes-or-no question: "is it free?" Line 9 prints $3. Line 10 prints false.

The table below compares good and vague names. Read each row as: "for this job, use this name, because of this, and not that vague name."

Good and vague function names for the same job
The jobGood nameWhy it worksVague name
Add up a cartcalculateTotalA verb, then the thing it gives back.total
Check an email addressisValidEmailIt reads like a yes-or-no question.check
Get a saved usergetUserIt says what value comes back.data
Turn cents into price textformatPriceIt says how the value changes.makeNice

Give each function one job. Say you want to name a function calculateAndPrintAndSaveTotal. That name is a sign to split it into smaller functions: one to calculate, one to print, and one to save.

A function that returns true or false often starts with is, has, or can: isValidEmail, hasDiscount, canCheckout. Then if (canCheckout(cart)) reads almost like a sentence: "if you can check out the cart".

Where you’ll use functions

Real programs are full of functions. You use them to:

  • Write a repeated job once.
  • Give a small idea a clear name.
  • Test one piece of code on its own.
Three small functions work out a billPop out in the code editor (opens in a new tab)JavaScript
function calculateSubtotal(items) {  return items.length * 10;} function addTip(total, rate) {  return total + total * rate;} function formatReceipt(name, total) {  return name + " owes $" + total;} const subtotal = calculateSubtotal(["tea", "cake"]);const withTip = addTip(subtotal, 0.2);console.log(formatReceipt("Maya", withTip));

Lines 1, 5, and 9 each start a small function with one job. Follow the values from line 13 down:

  1. Line 13 passes two items to calculateSubtotal. Each item costs 10, so it returns 20.
  2. Line 14 passes 20 and a 20% tip rate to addTip. It returns 24.
  3. Line 15 passes "Maya" and 24 to formatReceipt, then prints Maya owes $24.

Each function takes values in and returns one value. Each result is kept in a variable for the next step. This makes bugs easier to find. In the browser's debugger, you can step into a function to see its local variables. Or you can step over it when its name already tells you enough.

The total and the receipt text are made by separate functions. So a form can use the total without making receipt text too.

You will also see functions that run when a user clicks a button, that check what a user typed, and that turn values into text. Later lessons in this module show more ways to write and use functions: Default & rest parameters, Function expressions & callbacks, Arrow functions, and Recursion.

Common misconceptions

WATCH OUT
Common mistakes with functions
  • “A declaration runs its steps right away.” It doesn't. The steps run only when you call the function.
  • “Parameter and argument mean the same thing.” A parameter is the name in the declaration. An argument is the value in a call.
  • “Printing a value returns it.” Printing only shows the value on the screen. Only return gives it back to the call.
  • “Every function gives back a value you can see.” A function with no return gives back undefined.
  • “A local variable still exists after the call.” Code outside the function can never use it.
  • “The same name means the same variable.” A local variable can have the same name as an outer one. It hides the outer one but doesn't change it.

When a function prints something you didn't expect, look at the call first. Ask three questions:

  • Which arguments went in?
  • Did the function return a value?
  • Did it change an outer variable?

The Reading error messages and Debugging in the browser lessons help here too. Both error messages and the debugger show which functions were called.

Practice exercises

5 EXERCISES
Exercise 1 · Warm-upReturn the area of a rectangle

Write a function declaration called rectangleArea. Give it two parameters, width and height. Make it return the area. Then call it with 5 and 4, and print the result.

Starter codePop out in the code editor (opens in a new tab)JavaScript
function rectangleArea(width, height) {
  // return the area
}

console.log(rectangleArea(5, 4));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upGuess what a function with no return gives back

    What does the last line print? Don't give the value of result inside the function. Give the value that the call double(4) gives back.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    function double(number) {
      const result = number * 2;
    }
    
    console.log(double(4));

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFix a function that prints instead of returning

      Right now the code prints 10 and then NaN ("not a number"). That's because tip is undefined. Change the function so the last line prints 20.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      function getTip(total) {
        console.log(total * 0.2);
      }
      
      const tip = getTip(50);
      console.log(tip + 10);

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeGuess the output when two variables share a name

        Write the two lines the console prints, in order. This checks whether a local variable changes an outer variable with the same name.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        let label = "outer";
        
        function printLabel() {
          let label = "inner";
          console.log(label);
        }
        
        printLabel();
        console.log(label);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeChoose a clear function name

          You need a function that takes the items in a cart and returns their total price. Type a good name for it. More than one clear name is accepted.

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz

            8 QUESTIONS

            For each code question, follow these steps:

            1. Find each function declaration. Its steps wait.
            2. Find each call. Put the arguments into the parameters.
            3. Follow the return to see what the call gives back.
            4. Remember that local variables stay inside their function.
            Lesson quiz · 8 questionsScore: first tries count
            1. Question 1 of 8When JavaScript reads a function declaration, what does the declaration do?

              Choose an answer to see the explanation.

            2. Question 2 of 8What does the add(2, 5) call print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              function add(a, b) {
                return a + b;
              }
              console.log(add(2, 5));

              Choose an answer to see the explanation.

            3. Question 3 of 8In function greet(name) {} and the call greet("Ari"), which one is the argument?

              Choose an answer to see the explanation.

            4. Question 4 of 8What is the last line this code prints?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              function show(value) {
                console.log(value);
              }
              const result = show("hi");
              console.log(result);

              Choose an answer to see the explanation.

            5. Question 5 of 8A function runs return. What happens to the lines after it in the same function?

              Choose an answer to see the explanation.

            6. Question 6 of 8Two variables share the name word. What two lines does this code print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              let word = "outer";
              function sayWord() {
                let word = "inner";
                return word;
              }
              console.log(sayWord());
              console.log(word);

              Choose an answer to see the explanation.

            7. Question 7 of 8Which name is best for a function that checks whether an email address is valid?

              Choose an answer to see the explanation.

            8. Question 8 of 8This code calls sayHi above its declaration. What does it print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(sayHi());
              function sayHi() {
                return "hi";
              }

              Choose an answer to see the explanation.

            Key takeaways

            • A function declaration gives a set of steps a name. A call runs those steps.
            • Parameters are the names in the declaration. Arguments are the values in a call.
            • return gives one value back to the call and stops the function.
            • A function with no return gives back undefined.
            • Local variables live inside the function. Outer variables live around it, and the function can read and change them.
            • A good function name starts with a verb and describes one job.

            In one line: a function is a named set of steps. It can take values in, use its own local variables, and give one value back.

            Up next: Default & rest parameters.

            CompleteFrontend Clear concepts. Working examples.