Topic 3.1
Declaring and Calling Functions
In one line
A function is a named block of code you define once and run (call) as often as you like; it receives inputs through parameters, and sends a result back with return, or undefined when there is no return.
Think of it like this
A recipe card for pancakes. Writing the card is defining the function: the steps are on paper, but nothing is cooked yet. Cooking from the card is calling it, and you can cook it again tomorrow. The card says "take 2 eggs and some milk": those blanks are the parameters. The real eggs and milk you use today are the arguments. The pancakes you hand over at the end are the return value.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- Function
- A named block of code you can run again and again.
- Declare / define
- Write the function so it exists. Nothing inside it runs yet.
- Call / invoke
- Run the function by writing its name followed by
(). - Body
- The statements between the function's
{and}. - Parameter
- A name in the function's definition that will hold an input, like
nameinfunction greet(name). - Argument
- The actual value you pass in when you call, like
"Asha"ingreet("Asha"). - Return value
- The value a function sends back with
return. Without areturnit isundefined. - Early return
- A
returnnear the top that stops the function as soon as there is nothing more to do.
Step by step
01Define the function
Start with the keyword function, then a name, then the parameters in parentheses, then the body in braces. Writing this runs nothing yet: the browser only remembers that greet exists.
function greet(name) {
return "Hello, " + name + "!";
}02Call it with an argument
Write the name and parentheses, with the argument inside. JavaScript puts "Asha" into the parameter name, runs the body, and the call is replaced by the returned value.
const message = greet("Asha");
console.log(message); // Hello, Asha!
console.log(greet("Ravi")); // Hello, Ravi!03Follow the jump
A call is a jump: the program leaves the current line, runs the function's body from the top, and comes back to exactly where it left when it reaches return or the closing }. The returned value takes the place of the call.
04Leave arguments out, or add too many
JavaScript doesn't complain about the wrong number of arguments. A missing one makes its parameter undefined; extra ones are dropped (they are still in arguments, Topic 3.3).
greet(); // "Hello, undefined!"
greet("Mei", "extra"); // "Hello, Mei!"05Return early when you can
return stops the function at once. Use it to handle the special case first, so the main logic below isn't wrapped in an else.
function discount(total) {
if (total < 500) {
return 0; // nothing more to do
}
return total * 0.1; // only reached when total >= 500
}06No return means undefined
A function that never reaches a return gives back undefined. That's correct for functions that only print or change the page; it's a bug when you meant to compute a value and forgot to return it.
Try it yourself
- 1
Predict, then run
In the first example, add
console.log(greet("You") + " Welcome back."). Predict the exact line before you press Run. - 2
Add a parameter
Change
greettofunction greet(name, emoji)and return"Hello, " + name + "! " + emoji. Call it with two arguments, then with one. What appears where the emoji should be when you leave it out? - 3
Break the button on purpose
In the third example, change
addEventListener("click", showArea)toaddEventListener("click", showArea()). Predict what happens when you click, then check. (The breakIt section below explains it.)
Code & diagrams
`greet(...)` runs the function; `greet` alone is the function as a value. `length` is how many parameters it declares.
Preview
Console
Nothing logged yet.Expected console output
Hello, Ravi!
Hello, undefined!
Hello, Mei!
function
[Function: greet]
greet 1The last line logs the return value of `console.log` itself: it prints first, then returns `undefined`.
Console
(nothing was printed)Expected console output
negative zero positive
HI
shout returned: undefined
bare returned: undefined
printed first
undefined`area` computes and returns; `showArea` does a job on the page and returns nothing. Both are normal functions.
Preview
Console
Nothing logged yet.Break it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Call the function too early
In the button example, write addEventListener("click", showArea()) with parentheses.
Break #2
Put the value on the line after return
Write return alone on one line and the value on the next:
return
"Hello";
Myth vs fact
Myth
Parameters and arguments are the same thing.
Fact
Parameters are the names in the definition; arguments are the values passed in a call. name is a parameter, "Asha" is an argument.
Myth
A function without return returns nothing.
Fact
It returns undefined, a real value you can store and print.
Myth
JavaScript checks you passed the right number of arguments.
Fact
It never does. Missing arguments become undefined and extra ones are ignored, so your function must handle that (defaults in Topic 3.3 help).
Myth
console.log inside a function is the same as returning a value.
Fact
console.log only prints for you to read. The caller gets nothing it can use unless you return the value.
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
Each call creates a new execution context with its own parameters and local variables, pushed on the call stack and popped on return. Two calls never share locals, which is what makes recursion (Topic 3.8) possible.
- ▸
Arguments are passed by value, but for objects the value is a reference: reassigning a parameter never affects the caller, while mutating an object through it does (more in Topic 3.9 — Pure Functions and Side Effects).
- ▸
fn.lengthcounts parameters before the first one with a default value or a rest parameter:function f(a, b = 1, ...c) {}haslength1. Libraries use it to decide how to call a function (for example, test runners detect adonecallback that way). - ▸
Small, frequently called functions are cheap: V8 inlines hot small functions into their callers after optimisation, so splitting code into well-named functions almost never costs speed.
Remember this
- 1
A function is a block of code with a name that you can run whenever you want. You declare (define) it with the
functionkeyword, a name, a pair of parentheses( )for its inputs, and curly braces{ }around its body, the statements that run:function greet(name) { return "Hello, " + name + "!"; }. Defining a function runs nothing. The body only runs when you call (also called invoke) the function by writing its name followed by parentheses:greet("Asha"). - 2
Parameters are the names listed in the definition, like
nameinfunction greet(name). They act like local variables that exist only while the function runs. Arguments are the actual values you pass in the call, like"Asha"ingreet("Asha"). JavaScript matches them by position: the first argument goes into the first parameter, the second into the second, and so on. It never checks the count: a missing argument leaves its parameter asundefined, and extra arguments are ignored (they are still reachable, see Topic 3.3 — Default, Rest Parameters and Spread). - 3
returndoes two things at once: it ends the function immediately, and it sends a value back to the place that called it. Soconst message = greet("Asha");stores"Hello, Asha!"inmessage. Any code after areturnthat runs is never reached. A function can have severalreturnstatements (for example one inside anif, called an early return or guard clause), but only the first one reached runs. - 4
A function with **no
return**, or with a barereturn;, still gives something back: the special valueundefined. This is whyconsole.log(console.log("hi"))printshiand thenundefined. A function that only *does* something (prints, changes the page) instead of *computing* something is fine; just don't expect a useful value from it. - 5
Calling vs referring:
greetwithout parentheses is the function itself, a value you can store or pass around (Topic 3.7 — Callbacks and Higher-Order Functions).greet()with parentheses runs it and gives you its return value. Forgetting the()is a classic beginner bug: nothing runs, and you end up with the function instead of its result.typeof greetis"function", and every function has aname(greet.nameis"greet") and alength, the number of parameters it declares. - 6
Why bother with functions? They follow the DRY rule (Don't Repeat Yourself): fix a bug once and every caller gets the fix. They let you give a meaningful name to a few lines of code (
calculateTax(price)reads better than the maths). And they split a big problem into small pieces you can test one at a time. A good function does one job, has a name that starts with a verb (getTotal,showError,isValid) and is short enough to read in one glance.
Explain it without notes
What is the difference between a parameter and an argument?
What does return do, and what does a function return when it has no return statement?
What is the difference between greet and greet()?
What happens if you call a function with fewer or more arguments than it has parameters?
Practice
Write a function square(n) that returns n * n, and print square(7).
Write isEven(n) that returns true for even numbers and false otherwise, and test it with 4 and 7.
Write grade(score) that returns "A" for 90 and above, "B" for 75 and above, and "C" otherwise, using early returns (no else).
Trade-offs
- ↔
Many tiny functions make each piece easy to name and test, but too many layers make the flow hard to follow; split when a block has its own clear job or is repeated.
- ↔
Returning a value (and letting the caller print or display it) is more reusable than printing inside the function; printing inside is fine for quick scripts.
Done when you can
I can declare a function with parameters and call it with arguments.
I can explain the difference between a parameter and an argument.
I know that
returnends the function and that noreturnmeansundefined.I can tell
fn(the function) fromfn()(its result).I can write a function that uses early returns.