B Binance · The world's largest crypto exchangeBinance Sign up → AD OKX OKX · A leading global crypto exchangeOKX Sign up → AD
💻 Coding Basics · Lesson 5 / 10

Functions — Splitting Work into Small Named Machines

A function is a named bundle of code that takes input, processes it and hands back a result. The result must be handed back with `return`, not printed with `console.log`, so other code can keep using it — and that is also what makes it easy to test.

⏱ About 22 min ✍️ 5 practice questions 🧪 4 code exercises Updated 2026-10-09
🎯 By the end of this lesson you can
  • Write functions with parameters and return values, and call them
  • Explain the difference between return and console.log and use each where it fits
  • Write short functions as arrow functions and avoid the return trap that comes with curly braces
  • Split a long calculation into small pure functions and test them with inputs and expected values

1.What is a function? A machine that takes input and returns a result

In Lesson 1 we looked at a program as input → processing → output. A function is a small piece of that structure, cut out and given a name. Think of a vending machine. You put in money and press a button (input), and a drink (result) comes out even if you have no idea what happens inside. Once it is built, you can use the same vending machine again and again.

Without functions you have to copy the code every time you need the same calculation. Then, when the rule changes, you must find and fix every copy, and missing even one makes the results disagree. With a function, the rule lives in one place, and that is the only place you fix. And a name like vatOf(price) tells you what it does at a glance, so the code reads like a sentence.

Creating a function is called defining it, and using it is called calling it. Defining alone does nothing. The body runs only when you call it by adding parentheses after the name, as in vatOf(10000). Be careful: writing just vatOf without parentheses only refers to the function itself and does not run it.

Define once, call many times — a fictional 10% sales tax calculation
function vatOf(price) {
  return price * 0.1;
}
console.log(vatOf(10000));
console.log(vatOf(25000));
Output
1000
2500

2.Parameters and return values

The price inside the parentheses after the function name is called a parameter. It is the name of a "blank" used inside the function. The actual value you pass in when calling, 10000, is called an argument. When you call the function, the body runs with the argument stored in the parameter. With several parameters, separate them with commas; arguments go in the order they are written. Swap the order and you get a wrong result with no error, so order matters.

return hands the result back to where the function was called and ends the function right there. Lines below return do not run. If there is no return, or just return; with no value, the function returns undefined. If you pass too few arguments, the missing parameters also become undefined, and when used in a calculation they produce the NaN we saw in Lesson 2. JavaScript does not raise an error in these cases, so you have to check for yourself.

You can also set a value in advance to use when an argument is missing. Add = value after a parameter and it becomes a default value. In the code below, if you leave out rate, 0.1 is used. Defaults suit settings that are "usually this value," but putting a default on a value that must always be provided means you won't notice when you forget it, so use them with care.

A missing argument gives undefined → NaN; with a default, the default is used
function rectArea(w, h) {
  return w * h;
}
console.log(rectArea(3, 4));
console.log(rectArea(3));

function tax(price, rate = 0.1) {
  return price * rate;
}
console.log(tax(20000));
console.log(tax(20000, 0.05));
Output
12
NaN
2000
1000

3.`return` vs `console.log` — the most common confusion

When you first learn functions, the most confusing thing is the difference between returning a value and printing it on screen. Both seem to show a result, but they do completely different jobs. console.log writes a value on the screen for a person to look at, and the program cannot keep using that value. return hands the value to the code that called the function, so the receiving side can store it in a variable or feed it into another calculation.

showDouble in the code below only prints the result and does not return it. So when you store showDouble(4) in a variable, 8 appears on the screen, but the variable holds undefined, and adding 1 to it gives NaN. Think of it as the difference between punching numbers into a calculator to show an answer on its display and passing that answer on to the next calculation.

The grading of the exercises on this page works the same way. The grader calls your function and compares the value it gets back with the expected value. If you only print the correct answer with console.log inside the function, the right number appears on screen but grading fails. The principle is simple: functions that calculate hand back their result with return, and printing happens outside, where the function is called.

A function that only prints vs a function that returns
function showDouble(x) {
  console.log(x * 2);
}
function double(x) {
  return x * 2;
}
const a = showDouble(4);
console.log('value in a:', a, a + 1);
const b = double(4);
console.log('value in b:', b, b + 1);
Output
8
value in a: undefined NaN
value in b: 8 9
Comparing `return` and `console.log`
`return``console.log`
To whomThe code that called the functionThe person looking at the screen
Can the value be used further?Yes (in variables and calculations)No
Does the function end?It ends right thereIt continues to the next line
Exercise gradingGraded on the returned valueNot used for grading
Mainly usedInside functions that calculateChecking, debugging, final output

4.Arrow functions — a shorter syntax

A function can also be written in the shape const name = (parameters) => expression. This is called an arrow function. If the right side of the arrow is a single expression, its value is returned automatically, so you do not write return. Arrow functions are especially common when passing a function to another function, as with map and filter in Lesson 6, and you will see them often in AI-written code too.

There is one trap to watch for. If you use curly braces on the right of the arrow, it is treated like a regular function body from then on, and you must write return yourself. bad below writes only an expression inside the braces, forgets return, and returns undefined. Since no error occurs, it is easy to miss until you print the result. Remember: short ones go without braces; multi-line ones get braces and return together.

Within the scope of this course, functions written with function and arrow functions do the same job. There are finer differences (such as how they handle this), but you don't need them at the basics level. Neither is "better," so follow whatever style your teammates or project use.

With curly braces you must write return yourself
const add = (a, b) => a + b;
const square = (x) => x * x;
const bad = (x) => { x * x; };
const good = (x) => {
  const y = x * x;
  return y;
};
console.log(add(2, 3), square(4));
console.log(bad(4), good(4));
Output
5 16
undefined 16

5.Variables inside a function stay inside — scope

A variable created with let or const inside a function is visible only inside that function. This is called scope. When the function ends, the variables inside it disappear too, so using that name outside gives a ReferenceError. The message is not defined means "no such name is visible here." The exact wording of the message may differ slightly between browsers.

It may seem inconvenient at first, but this rule keeps functions from interfering with each other. Several functions can each use the name total inside without mixing them up. If you want to use a value calculated inside a function from outside, don't quietly change an outside variable; hand it back with return. The same goes for let and const created inside the curly braces of loops and conditionals: they are visible only inside those braces (which is why we put the accumulator above the loop in Lesson 4).

Outside the function, the variable inside cannot be seen
function makeTotal() {
  const inside = 100;
  return inside + 1;
}
console.log(makeTotal());
console.log(inside);
Output
101
ReferenceError: inside is not defined

6.Splitting into small functions

If you write a long calculation as one big lump, it is hard to find where it went wrong. Split it instead into several small functions that "do one thing each" and assemble them, and you can test each part separately while the names serve as explanations. Function names reveal what they do with a verb, like getTotal or isAdult, and by convention functions that return true or false start with is or has.

The question that tells you where to split is: "Can I describe this part in one sentence?" If it becomes a single sentence, like "add up all the item prices" or "decide the shipping fee from the total," that is one function. If your description contains "and" several times, that is a sign it can be split further. However, chopping a one-line calculation too finely actually makes code harder to read, so split into units meaningful enough to deserve a name.

ExampleA fictional online shop's rule: add up all item prices; if the total is 50,000 won or more, shipping is 0 won, otherwise add 3,000 won. How would you split this calculation into functions?
function subtotal(prices) {
  let sum = 0;
  for (const p of prices) {
    sum += p;
  }
  return sum;
}
function shippingFee(sum) {
  return sum >= 50000 ? 0 : 3000;
}
function orderTotal(prices) {
  const sum = subtotal(prices);
  return sum + shippingFee(sum);
}
console.log(orderTotal([20000, 10000]));
console.log(orderTotal([30000, 20000]));
Output
33000
50000
  1. Step 1, break it into sentences: "add up all the prices" / "decide the shipping fee from the total" / "add the two to get the final amount."
  2. Step 2, the part functions: subtotal(prices) is the running-total pattern from Lesson 4, and shippingFee(sum) is a conditional from Lesson 3.
  3. Step 3, assemble: orderTotal(prices) just calls the two parts. If the rule changes (say, a 60,000 won threshold), you fix only shippingFee.
  4. Check: [20000, 10000] → total 30,000 + shipping 3,000 = 33,000. [30000, 20000] → total 50,000 (the boundary value; "or more," so shipping is free) = 50,000.
AnswerSplit the total, the shipping fee and the final amount into separate functions and assemble them: 33000, 50000
condition ? value1 : value2 is a short conditional expression (the ternary operator) that becomes value1 if the condition is true and value2 if it is false. Think of it as the if/else of Lesson 3 written on one line. When it gets long, if is easier to read.

7.Pure functions and easily tested code

A function that always returns the same result for the same input, and does not change anything outside it such as variables or the screen, is called a pure function. double(4) is 8 no matter when you call it. In contrast, addVisit below changes the outside variable visits, so the same call returns a different value each time. With functions like that, the result depends on "what has happened so far," which makes causes hard to trace.

The biggest advantage of pure functions is that they are easy to test, because all you need is a table of "this input gives this result." When you write a function, pick a few normal cases, boundary values (0, an empty list, a value exactly equal to a threshold) and odd inputs, write down the expected values first, and compare them with the results. That is exactly how the exercises on this page are graded, and it is the same method we use in Lesson 10 to verify AI-written code.

Of course, not every function can be pure. Printing to the screen, saving files and sending to a server exist precisely to change the outside world. The trick is to keep calculations in separate pure functions and gather the outside-changing work in a few places at the edges. Then the error-prone calculations can be tested with tables, and the outside-changing parts are short enough to check by eye.

Same call, different results (not pure) vs always the same result (pure)
let visits = 0;
function addVisit() {
  visits++;
  return visits;
}
console.log(addVisit(), addVisit());

const nextCount = (n) => n + 1;
console.log(nextCount(0), nextCount(0));
Output
1 2
1 1
Testing with a table of inputs and expected values — in this fictional rule adulthood starts at 19, so always include the boundary 19
const isAdult = (age) => age >= 19;
function check(input, want) {
  const got = isAdult(input);
  const ok = got === want;
  console.log(input, ok ? 'pass' : 'fail');
}
check(18, false);
check(19, true);
check(0, false);
Output
18 pass
19 pass
0 pass

📌 Key points

  • A function is named code that takes input (parameters), processes it and hands back the result with return
  • console.log only shows a value to people; for other code to use it, you must return it
  • A missing argument is undefined, and no return means undefined — this can quietly become NaN
  • If you use curly braces in an arrow function, you must write return yourself
  • Split code into small pure functions that can each be described in one sentence, and they are easy to test with input/expected-value tables

✍️ Practice questions

Answer first, then open "Answer and explanation".

Q1. Given function f(x) { console.log(x + 1); }, what is in r after const r = f(2);?

⭕ Correct

❌ Not quite — see the explanation

Answer and explanation
Answer ② undefined

f only prints 3 on the screen and has no return, so it returns undefined. To keep using the value, change it to return x + 1;.

Q2. With const g = (x) => { x * 2; };, what does g(5) give?

⭕ Correct

❌ Not quite — see the explanation

Answer and explanation
Answer ② undefined

With curly braces it is treated as a body, so you must write return yourself. Drop the braces as in (x) => x * 2, or change it to { return x * 2; }.

Q3. What happens if you call function area(w, h) { return w * h; } as area(5)?

⭕ Correct

❌ Not quite — see the explanation

Answer and explanation
Answer ③ NaN

No argument is passed for h, so it is undefined, and 5 * undefined is NaN. JavaScript raises no error when the number of arguments differs.

Q4. Which of the following is a pure function?

⭕ Correct

❌ Not quite — see the explanation

Answer and explanation
Answer ② A function that returns the larger of two numbers it receives

The larger of two numbers is always the same for the same input and changes nothing outside. Changing outside variables, relying on something outside the input such as the time, or printing to the screen are not pure.

Q5. What kind of error occurs if you use, outside a function, a variable created with const inside it? Write the name of the error.

Answer and explanation
Answer ReferenceError (… is not defined)

Variables inside a function are visible only inside that function. If you need the value outside, get it back with return and store it in a variable.

🧪 Code lab

A calculating function is graded only if it returns its value. Work through the exercises in order, from fixing code that only prints to assembling small functions.

Your code runs only inside an isolated sandbox in this browser and is never sent to a server. It has no network access and is stopped after 2 seconds. Edited code is saved only in this browser. Ctrl+Enter (⌘+Enter) runs it; Tab inserts two spaces (press Esc, then Tab, to move on).

JavaScript is off, so the code can't run here, but you can still read each task, its starter code, the automatic checks and a sample solution.

1Celsius to Fahrenheit

Write a function cToF(c) that takes a Celsius temperature c and returns the Fahrenheit temperature. The formula is Fahrenheit = Celsius × 9 / 5 + 32. Example: cToF(100) is 212.

Automatic checks
  • cToF(0)expected 32
  • cToF(100)expected 212
  • cToF(-40)expected -40
  • cToF(36.5)expected 97.7
💡 Hint

Without return, the function returns undefined.

Show a sample solution
function cToF(c) {
  return c * 9 / 5 + 32;
}

2Fix a function that only prints

A fictional online shop's shipping function shippingFee(sum) should return 0 if the total sum is 50,000 won or more, and 3000 otherwise. The starter code only prints the value on screen, so it fails grading. Fix it so it returns the value.

Automatic checks
  • shippingFee(12000)expected 3000
  • shippingFee(50000)expected 0
  • shippingFee(49999)expected 3000
  • shippingFee(80000)expected 0
💡 Hint

Change console.log(value) to return value. 50,000 is the boundary value, and since the rule says "or more," shipping is free.

Show a sample solution
function shippingFee(sum) {
  if (sum >= 50000) {
    return 0;
  }
  return 3000;
}

3Assemble small functions

Write orderTotal(prices), which takes an array of prices prices and returns the final payment amount: the total plus shipping (0 won if the total is 50,000 won or more, otherwise 3,000 won). However, an empty array means there is no order, so return 0. Use subtotal and shippingFee from the starter code.

Automatic checks
  • orderTotal([20000,10000])expected 33000
  • orderTotal([30000,20000])expected 50000
  • orderTotal([])expected 0
  • orderTotal([49999])expected 52999
  • orderTotal([60000,5000])expected 65000
💡 Hint

Check for an empty array with prices.length === 0. Put that check first and return immediately, and the calculation below does not run.

Show a sample solution
function subtotal(prices) {
  let sum = 0;
  for (const p of prices) {
    sum += p;
  }
  return sum;
}
const shippingFee = (sum) => (sum >= 50000 ? 0 : 3000);

function orderTotal(prices) {
  if (prices.length === 0) {
    return 0;
  }
  const sum = subtotal(prices);
  return sum + shippingFee(sum);
}

4Keep a value within a range (arrow function)

Write an arrow function clamp that keeps the number x between min and max (inclusive) and returns it. If x is less than min, return min; if it is greater than max, return max; otherwise return x unchanged. Example: clamp(15, 0, 10) is 10. (Assume min is not greater than max.)

Automatic checks
  • clamp(15, 0, 10)expected 10
  • clamp(-3, 0, 10)expected 0
  • clamp(7, 0, 10)expected 7
  • clamp(0, 0, 10)expected 0
  • clamp(10, 0, 10)expected 10
💡 Hint

It is an arrow function with curly braces, so every branch needs a return. You can also nest Math.min and Math.max to write it on one line.

Show a sample solution
const clamp = (x, min, max) => {
  if (x < min) return min;
  if (x > max) return max;
  return x;
};

🤖 Try asking AI like this

Copy a prompt and replace the [ ] parts with your own situation. Don't take the answer on trust — check it against this lesson.

When you want to split long code into functions

Split the JavaScript code below into small functions that each "do just one thing." Summarize each function's name, parameters and return value in a table, and make the calculating functions `return` their results without `console.log`. Don't change the behavior, and explain each change line by line. Code: [paste here]

When you need a test table for a function you wrote

Make a table of 6 test inputs and expected values for the following function: 2 normal cases, 3 boundary values (0, empty value, a value equal to the threshold) and 1 odd input, with a one-line explanation of why each expected value is what it is. What the function does: [describe it] Code: [paste here]

When `return` and `console.log` confuse you

Make 3 very short examples that show the difference between `return` and `console.log` in JavaScript. Don't tell me the output in advance; when I answer with my prediction, tell me whether I'm right and why.

🧰 Related tools

Tools for checking and tidying the JSON, regular expressions and text from this lesson. Don't paste real personal data or passwords.

References
  • MDN Web Docs — JavaScript Guide: Functions
  • MDN Web Docs — reference for arrow function expressions, the return statement and default parameters
  • General concepts of pure functions and unit testing as covered in introductory programming textbooks

Reached every goal above? Mark the lesson complete.

💻 Coding Basics

  1. 1What Is a Program? — Breaking Work into Sequence, Choice, and Repetition
  2. 2Values, Variables, and Types — Putting Name Tags on Values
  3. 3Conditionals — Taking Different Paths Depending on the Situation
  4. 4Loops — Doing the Same Thing Many Times, Exactly
  5. 5Functions — Splitting Work into Small Named Machines
  6. 6Arrays and Objects — Storing and Handling Data
  7. 7Strings and Text — Cutting, Finding and Replacing Characters
  8. 8Debugging and Reading Errors — Turning Red Text into Clues
  9. 9Simple Automation — Spreadsheet Math and Text Cleanup in Code
  10. 10Reading and Verifying AI-Written Code — Tests, Security, Licenses, Privacy
📚 Worth reading
📊Using AI for Spreadsheets, and Checking the Formulas→ 💻AI Coding Assistants: Security and Licence Risks→ 💬Practising Conversation in a Foreign Language with AI→ ⚙️Finding Work Tasks Worth Automating with AI→
← Foundations for the AI Era