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.
function vatOf(price) {
return price * 0.1;
}
console.log(vatOf(10000));
console.log(vatOf(25000));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.
undefined → NaN; with a default, the default is usedfunction 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));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.
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);8 value in a: undefined NaN value in b: 8 9
| `return` | `console.log` | |
|---|---|---|
| To whom | The code that called the function | The person looking at the screen |
| Can the value be used further? | Yes (in variables and calculations) | No |
| Does the function end? | It ends right there | It continues to the next line |
| Exercise grading | Graded on the returned value | Not used for grading |
| Mainly used | Inside functions that calculate | Checking, 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.
return yourselfconst 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));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).
function makeTotal() {
const inside = 100;
return inside + 1;
}
console.log(makeTotal());
console.log(inside);101
ReferenceError: inside is not defined6.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.
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]));33000 50000
- 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."
- Step 2, the part functions:
subtotal(prices)is the running-total pattern from Lesson 4, andshippingFee(sum)is a conditional from Lesson 3. - Step 3, assemble:
orderTotal(prices)just calls the two parts. If the rule changes (say, a 60,000 won threshold), you fix onlyshippingFee. - 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.
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.
let visits = 0;
function addVisit() {
visits++;
return visits;
}
console.log(addVisit(), addVisit());
const nextCount = (n) => n + 1;
console.log(nextCount(0), nextCount(0));1 2 1 1
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);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.logonly shows a value to people; for other code to use it, you mustreturnit- A missing argument is
undefined, and noreturnmeansundefined— this can quietly becomeNaN - If you use curly braces in an arrow function, you must write
returnyourself - 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
🧪 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.
cToF(0)expected32cToF(100)expected212cToF(-40)expected-40cToF(36.5)expected97.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.
shippingFee(12000)expected3000shippingFee(50000)expected0shippingFee(49999)expected3000shippingFee(80000)expected0
💡 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.
orderTotal([20000,10000])expected33000orderTotal([30000,20000])expected50000orderTotal([])expected0orderTotal([49999])expected52999orderTotal([60000,5000])expected65000
💡 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.)
clamp(15, 0, 10)expected10clamp(-3, 0, 10)expected0clamp(7, 0, 10)expected7clamp(0, 0, 10)expected0clamp(10, 0, 10)expected10
💡 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.
- Text Diff CheckerPaste the output from before and after splitting code into functions side by side to confirm the behavior did not change while you tidied up.
- Markdown EditorWrite function names, inputs and expected values as a Markdown table to keep your test list organized and easy to share with others.
- Quick NotepadUse it as a place to collect small functions you use often, so you can take them out again in the next exercise.
- 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.
Storage is unavailable in this browser, so this lasts only for this page.💻 Coding Basics
- 1What Is a Program? — Breaking Work into Sequence, Choice, and Repetition
- 2Values, Variables, and Types — Putting Name Tags on Values
- 3Conditionals — Taking Different Paths Depending on the Situation
- 4Loops — Doing the Same Thing Many Times, Exactly
- 5Functions — Splitting Work into Small Named Machines
- 6Arrays and Objects — Storing and Handling Data
- 7Strings and Text — Cutting, Finding and Replacing Characters
- 8Debugging and Reading Errors — Turning Red Text into Clues
- 9Simple Automation — Spreadsheet Math and Text Cleanup in Code
- 10Reading and Verifying AI-Written Code — Tests, Security, Licenses, Privacy