Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Let me set the boundaries first. This site already has quite a few JavaScript basics guides: array methods covers lists, string methods covers text, numbers and Math covers arithmetic, regular expressions covers patterns, and destructuring, classes and prototypes, closures, the event loop, modules, Fetch, the DOM, and localStorage each have their own guide. This one does not repeat them; it covers one thing only: functions themselves. You call functions all day when you build a web page. Computing an order total is a function, the code that runs when you click "add to cart" is a function, and even Array.map and addEventListener take functions as arguments. The "Greenstone Cafe" used below is the same fictional practice project as in earlier guides: a small web tool that takes orders for a street-corner cafe. Earlier guides covered its styling, its layout, and its arithmetic; this one covers how its order page wraps repeated work into functions: computing what one order costs, joining dish names into one sentence, refreshing the page after a button click. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. All syntax and behavior about functions comes from three official MDN documents: "Functions — reusable blocks of code", "Arrow function expressions", and "Rest parameters"; the sources are listed in the meta information and the evidence record for this article. After reading it, you should be able to do four things: tell a function declaration from a function expression, write parameters and default values, use rest parameters and spread syntax, and know when an arrow function works and when it loses "this". This guide does not cover generator functions, decorators, or the full rules of "this"; step nine covers only the one line that matters for arrow functions and "this".
Step 1: A function is a block of code you can call again and again
MDN's Learn article starts with a reassuring fact: you have already been using functions, we just never named them. Whenever you write a name followed by a pair of parentheses, and it is not a language structure like a for loop, a while loop, or an if statement, you are using a function. The replace method that edits strings is a function, the join method that assembles arrays is a function, and Math.random is a function too. There are two kinds: built-in functions that ship with the browser, and custom functions that you write yourself. Some built-in functions cannot even be written in JavaScript; behind them is low-level browser code written in system languages like C++. A custom function is one you name and write the logic for, such as the two examples in the MDN article: a draw function that paints 100 random circles, and a random function that returns a whole number between 0 and a given number. The random function is only three lines: function random(number), with return Math.floor(Math.random() * number) inside. It exists for a practical reason: the built-in Math.random only gives a decimal between 0 and 1, and you wanted a whole number up to 100, so you wrapped it. The benefit of a function is one sentence: write a block of code once, call it as many times as you like. Defining a function only writes it down; it does not run until you call it, which you do by writing its name followed by parentheses, like draw(). On the cafe order page, computing an order total is exactly such a function: write calcTotal once, and call it whenever the menu, the quantities, or the discount changes, instead of copying the addition ten times across the page. Functions can also call other functions; draw calls random three times. The check for this section: when you see a name plus parentheses, first ask whether it is a definition or a call. A definition wraps the work up; a call makes the work actually run.
Step 2: Declarations and expressions: hoisting only helps one of them
There are two basic ways to write a function, and the easiest thing for beginners to mix up is how they behave when you call them early. The first is a function declaration: function myFunction(), with alert("hello") inside. MDN states plainly that this form is hoisted, which means you can call the function above its definition and it will still work. Hoisting means JavaScript collects function declarations before it really starts running, so a definition written later can still be found by a call written earlier. The second is a function expression: an anonymous function, one with no name, handed to a variable, like const greet = function () { alert("hello"); }. MDN states equally plainly that this form is not hoisted; calling it before it appears throws an error. Anonymous functions show up most often where one function expects to receive another function as an argument, for example the second argument of addEventListener. Neither form is absolutely better, but you should know which one you picked: use declarations for utility functions the whole page needs, because they can sit at the bottom of the file and callers above them do not have to worry about order; use expressions or arrow functions for a callback that is only used in one place, written exactly where it is used. On the cafe order page, computing totals and formatting amounts are page-wide utilities, so write them as function declarations at the bottom of the file and call them freely from the button logic at the top; the small piece of logic that runs when you click "add to cart" can be an anonymous function written straight into addEventListener, with no separate name. The check is simple: if calling a function before its definition works without an error, it must be a declaration; if it errors saying it is not defined yet, it is an expression. Hoisting helps declarations only, not expressions; do not expect the benefits of both from one form.
Step 3: Parameters and arguments: the names have to line up
Some functions need nothing when you call them, like Math.random(), whose parentheses stay empty; others cannot do their job without values, like replace, which needs "what to find" and "what to replace it with". MDN draws a sharp line between two words here. In everyday speech they can be mixed, but in code they must not be: parameters are the variable names listed in a function definition, while arguments are the values actually passed in when the function is called. In function random(number), number is a parameter; in the call random(100), 100 is the argument. Multiple parameters or arguments are separated by commas, and order is how they match up: the first argument goes to the first parameter, the second to the second, and a wrong order gives a wrong result. On the cafe order page, if the total function is written as calcTotal(price, count), the call must be calcTotal(1990, 2), price first and count second; writing calcTotal(2, 1990) treats the count as the price and the bill comes out ten times too big. Two more traps catch beginners: first, passing too few arguments is not an error; the missing parameter is simply undefined inside the function, and adding undefined gives NaN, so the bill quietly becomes NaN. Second, passing too many arguments is not an error either; the extra ones are ignored, and the function only sees the parameters it declared. MDN's example confirms the same idea: the join method's parameter is optional, so calling it with no argument uses a comma as the default separator, and passing a space joins with spaces. The check for this section is simple: every time you call a function, count the arguments, then match them against the parameters in order. If the count and the order both line up, the function has a chance to compute correctly; if the count is off, check whether the next section's default values or step five's rest parameters are what you need.
Step 4: Default parameters: the call still works when you pass less
Some parameters do not have to be passed every time, and MDN's fix is to write an equals sign and a default value after the parameter name. The article's example is clean: function hello(name = "Chris"), which prints Hello plus the name. Calling hello("Ari") gives Hello Ari, and calling hello() with nothing gives Hello Chris, because the default steps in. A default only kicks in in two cases: when the call passes no argument for that parameter at all, or when it passes undefined. Any other value, even an empty string or 0, wins over the default, and the function uses what you passed. Remember this distinction: an empty string means "I passed an empty name", while undefined means "I passed no name"; they are completely different. A default can also be an expression, computed from an earlier parameter or by calling another function, but beginners only need the simple form first. On the cafe order page, default parameters are most useful for "optional configuration": a display function like formatPrice(cents, symbol = "¥") shows ¥39.80 when called as formatPrice(3980), and you only pass the second argument when you want a different symbol; a discount function like applyDiscount(total, rate = 0.9) applies a 10 percent discount unless a different rate is passed. One more habit goes with defaults: put them at the end of the parameter list, required parameters first and optional ones last. Then a call that only passes the first few arguments still works, and nobody has to count commas to skip a middle parameter. The check: after writing a function with a default, call it once without that argument and see whether the result is the default, then call it once passing undefined and see whether the result is the same. If both are right, the default is written correctly.
Step 5: Rest parameters: collect the extras into one array
What if the number of arguments is not fixed? On the order page, splitting one table's bill could involve 2 people or 8 people, and the function definition cannot know in advance how many numbers will arrive. MDN's Rest parameters reference gives the answer: rest parameters. Prefix the last parameter with three dots, like function sum(...theArgs), and every extra argument is collected into a real array. The article's example is verified: sum(1, 2, 3) gives 6, and sum(1, 2, 3, 4) gives 10, because theArgs is [1, 2, 3] and [1, 2, 3, 4] in turn, and adding them up gives those answers. Rest parameters have four hard rules, and breaking any one of them is a syntax error: a function can have only one rest parameter; it must be the last parameter in the definition; no trailing comma is allowed after it; and it cannot have a default value. MDN's myFun example shows the split: function myFun(a, b, ...manyMoreArgs), called as myFun("one", "two", "three", "four", "five", "six"), gives a as "one", b as "two", and manyMoreArgs as ["three", "four", "five", "six"]. With only two arguments, manyMoreArgs is an empty array [], not undefined; with only one, b is undefined and manyMoreArgs is still []. A rest parameter is a real array, so array methods work on it directly: MDN's multiply example is function multiply(multiplier, ...theArgs), returning theArgs.map((element) => multiplier * element), and multiply(2, 15, 25, 42) gives [30, 50, 84], verified, since 2 times 15 is 30, 2 times 25 is 50, and 2 times 42 is 84. There is also the sortRestArgs example: function sortRestArgs(...theArgs) returning theArgs.sort(), and sortRestArgs(5, 3, 7, 1) gives [1, 3, 5, 7]. That is the biggest advantage of rest parameters over the old arguments object: arguments is not a real array, so calling sort on it throws an error, while a rest parameter is an array and sort, map, forEach, and pop all work on it directly. On the cafe order page, rest parameters fit "an unknown number of similar things": calcTableTotal(...prices) adds up 3 dishes or 8 dishes the same way, and a logging function logOrder(...notes) records as many notes as you like. The check: fixed count, use ordinary parameters; unknown count, use a rest parameter; and leave the old arguments object alone whenever you can.
Step 6: Spread syntax: the opposite direction, splitting an array open
Rest parameters collect many arguments into one array; spread syntax does exactly the opposite: it splits one array open into many arguments. It uses the same three dots, for example Math.max(...scores). MDN's Rest parameters page links to the Spread syntax reference at the end, and spread is the mirror image of rest using the same symbol; this guide writes it from that comparison, and the spread reference page itself is not one of the three sources read in full, as the evidence record explains. The idea itself is straightforward: a function only takes separate values, not an array, and you happen to hold an array, so you split it open with spread. A verified example: scores is [12, 45, 7, 33], and Math.max(...scores) gives 45, exactly the same as Math.max(12, 45, 7, 33); writing Math.max(scores) directly passes one array and gives NaN, because Math.max does not understand arrays. Spread also works inside array literals to join arrays: const all = [...hot, ...cold] merges the hot-dish array and the cold-dish array into one full menu; and it works in calls that take several arrays, like sum(...a, ...b). On the cafe order page, spread shows up most often in two places: first, finding the highest or lowest price with Math.max(...prices) and Math.min(...prices) instead of writing a loop to compare; second, merging two lists, such as today's specials and the regular menu, into one full menu. The easy thing to mix up is the direction: writing ...theArgs in a function definition means "collect", while writing ...scores in a function call means "split open". It is the same symbol, but in a definition and in a call it means exactly the opposite. The check: before a call, ask whether this function wants separate values or one whole array. If it wants separate values and you hold an array, split it with spread; if it wants one whole array and you hold separate values, collect them with a rest parameter in the definition. Get both directions right and arguments never land in the wrong place again.
Step 7: Return values: no return means you get undefined
When a function finishes computing, it hands the result back with return. In MDN's Learn article, the last line of the random function is return Math.floor(Math.random() * number), so calling random(100) gives back a whole number between 0 and 99, and that value is the expression after return. Return has two rules: first, the function stops immediately when it reaches a return, and no code after it runs; second, a function with no return always gives back undefined when called. Undefined is not an error; it is JavaScript telling you "this function handed back nothing". This rule causes the most painful bug on the order page: a total function that adds the prices up but forgets to write return hands the caller undefined, and displaying undefined as an amount shows undefined or NaN on the page. The other way around, a function whose job is only to "do something" rather than "hand back a value" is fine without a return, for example a function that adds a line to the page when a button is clicked. Its job is to change the page, not to compute a value, so nobody expects anything back from calling it. Return can only hand back one value at a time; to hand back several, wrap them in an object or an array first, like return { total: 3980, count: 2 }, and let the caller take what it needs from the object. Arrow functions have a shorthand tied directly to return: when the body is a single expression, you can drop the braces and the return keyword and the value is handed back automatically; the next step explains it in detail. The check is simple: after writing a function, ask whether the caller needs a value back. If yes, it must have a return; if no, accept that it returns undefined. Printing the result right after the call is the cheapest way to check.
Step 8: Arrow functions: three shorthand rules
Arrow functions are a shorter way to write anonymous functions, and MDN's Arrow function expressions reference takes a traditional anonymous function down to the shortest form step by step, with every step a valid way to write it. Start from function (a) { return a + 100; }. First, drop the word "function" and put an arrow between the parameter and the opening brace: (a) => { return a + 100; }. Second, drop the braces and the return: (a) => a + 100, and the value is returned implicitly. Third, with a single parameter you can drop the parentheses too: a => a + 100. Remember the three shorthand rules one by one: parentheses can only be dropped when the function has a single simple parameter. With multiple parameters, no parameters, or default, destructured, or rest parameters, the parentheses must stay. Braces can only be dropped when the function body is a single expression that is returned directly. With several statements in the body, the braces must stay and the return value must be written out explicitly with the return keyword. An arrow function has no name of its own; to call it, assign it to a variable, like const add = (a, b) => a + b, or pass it straight to another function as a callback. MDN's example is verified: materials is ["Hydrogen", "Helium", "Lithium", "Beryllium"], and materials.map((material) => material.length) gives [8, 6, 7, 9], because the four words are 8, 6, 7, and 9 letters long. There is also the object-literal trap: to return an object directly from an arrow function, you cannot write () => { foo: 1 }, because the braces are read as a function body, foo is read as a label, and the call returns undefined. The correct form wraps the object in parentheses: () => ({ foo: 1 }). On the cafe order page, arrow functions fit short callbacks best: turning a menu array into a price array is menu.map((item) => item.price), and filtering orders to the ones still waiting is orders.filter((order) => order.status === "waiting"). The check: one line, use an expression body; more than one line, use a block body with return, and do not trade readability away to save two lines.
Step 9: The "this" of arrow functions: they do not have their own
The biggest difference between arrow functions and ordinary functions is not length but "this". MDN's Arrow function expressions reference says it at the start: arrow functions should only be used for non-method functions because they do not have their own "this". In an ordinary function, "this" is decided when the function is called: whoever calls it, that is what "this" is. In an arrow function, "this" is fixed when the function is defined: it uses the "this" of the scope around it, and the way it is called cannot change it. MDN's example makes the point well: an object obj holds i equal to 10, b is an arrow function, and c is an ordinary method. Calling obj.b() prints undefined and the global object; calling obj.c() prints 10 and the object itself. The arrow function b sees the "this" from outside its definition, not obj. Three consequences follow. First, call, apply, and bind are useless on arrow functions. MDN verifies it: an ordinary add function called with call and obj gives 100 plus 1 plus 2 plus 3, which is 106; an arrow add function called with the same obj gives 48, because it still uses the global num equal to 42, and 42 plus 1 plus 2 plus 3 is 48, and bind cannot change it either. Second, arrow functions cannot be used as constructors: calling one with new throws an error saying it is not a constructor, and it has no prototype property. Third, arrow functions have no arguments object of their own; writing arguments inside one refers to the arguments of the enclosing function. To collect an unknown number of arguments, MDN explicitly recommends rest parameters instead: function foo(n) with const f = (...args) => args[0] + n inside, and calling foo(1) gives 11, because args[0] is 10 and 10 plus 1 is 11. There is also the case where an arrow function saves the day: in MDN's setTimeout example, an ordinary function as the callback loses "this" to the global scope and count comes out as NaN; swapping in an arrow function keeps "this" in the outer method, count goes from 10 to 11, and 11 is printed. An arrow function written as a class field also holds "this" firmly on the instance, and even calling it on its own after destructuring does not lose it; MDN calls this an auto-bound method, while warning that every instance creates one more function and uses a little more memory. The rule for the cafe order page: use ordinary functions for object methods, constructors, and anywhere "this" must mean the object itself; use arrow functions for short callbacks, small logic inside setTimeout, and anywhere you want to keep the outer "this". The check: before writing an arrow function, ask whose "this" should be inside it. If you cannot answer, do not use an arrow function as a method.
Step 10: Passing functions as arguments: callbacks and higher-order functions
In JavaScript, a function can be passed around like a number or a string: handed to another function as an argument, or handed back as a return value. A function that takes another function as an argument is called a higher-order function. MDN's Learn article gives the most direct example, addEventListener: textBox.addEventListener("keydown", logKey), where the first argument is the event name "keydown" and the second is the function logKey. When the user presses a key, the browser calls logKey and passes in an event object carrying information about the key pressed. You can also skip the separate logKey definition and write the anonymous function straight into the call: textBox.addEventListener("keydown", function (event) { console.log(`You pressed "${event.key}".`); }), and as an arrow function that becomes (event) => { console.log(`You pressed "${event.key}".`); }. Array methods are the most common place for callbacks: MDN's Arrow function expressions reference verifies that with arr as [5, 6, 13, 0, 1, 18, 23], arr.reduce((a, b) => a + b) gives 66, since 5 plus 6 plus 13 plus 0 plus 1 plus 18 plus 23 is exactly 66; arr.filter((v) => v % 2 === 0) gives [6, 0, 18], the only even numbers in the array; and arr.map((v) => v * 2) gives [10, 12, 26, 0, 2, 36, 46], each number doubled, all verified. The trap beginners hit hardest here is mixing up "passing a function" and "calling a function": addEventListener("click", handleClick) hands the function itself over, so the browser calls it when the click happens; writing addEventListener("click", handleClick()) runs the function at once, at the moment of registration, and passes its return value, undefined, so nothing happens on click. On the cafe order page, callbacks are everywhere: clicking "add to cart" passes a function, a change in an input box passes a function, and every map, filter, and reduce passes a function. There is a cheap way to tell whether a callback is written right: look at the parentheses. Passing a function has no parentheses after its name; calling a function does. To pass arguments into a callback, wrap the call in an arrow function, like () => addItem("latte"), instead of writing addItem("latte") directly. The conclusion of this section: passing a function as an argument passes "work to run later", not "a result computed now".
Step 11: Scope: variables inside a function are invisible outside it
A function is not only a tool for wrapping code; it is also a box that locks variables away. MDN's Learn article explains scope with an apartment building: each apartment is private, like function scope, where variables and functions defined inside a function can only be touched by code inside that function; the pool, gym, and rec room are shared by everyone, like the global scope, where anything defined globally can be used anywhere. The article's example is concrete: x equal to 1 is defined globally, y equal to 2 is defined inside function a, z equal to 3 is defined inside function b, and an output function prints a value to the page. Calling output(x) from the console prints 1; calling output(y) or output(z) throws an error at once, a ReferenceError saying y or z is not defined, because y and z are locked inside their own functions. Calling output(y) from inside function a, on the other hand, prints normally, because the call and the variable sit in the same scope; calling output(x) from inside function a also works, because x is global and visible everywhere. One more rule goes with it: variables declared with let and const inside the braces of an if statement or a for loop are locked inside those braces too, and invisible outside; the old var keyword behaves differently, hoisting up to function scope or even global scope, so it can be read outside the if. That inconsistency is one reason MDN recommends using only let and const. On the cafe order page, scope decides directly whether variable names collide: a total variable inside the total function and another total variable inside the discount function are each locked away and never interfere; but if total is defined globally, both functions write to the same one, and nobody can say in the end whose change produced the final number. The check: when you get a ReferenceError saying a variable is not defined, do not rush to add a definition. First check whether the variable is locked inside another function; if it is, either pass the value in as a parameter or hand it out with return, and do not make it global just to save effort.
Step 12: Pre-launch checklist, with a breakdown chart
The chart below shows a fictional breakdown of 100 function mistakes in one month on the Greenstone Cafe order page. The numbers are invented examples, matched against the traps from the eleven steps above: forgetting to write return, 19 times, the most; using an arrow function as a method and losing "this", 17 times; passing arguments in the wrong order, 15 times; writing rest and spread in the wrong direction, 14 times; putting a default parameter after a rest parameter, 12 times; adding an extra pair of parentheses in a callback so the function ran early, 11 times; an anonymous function with no name, impossible to find while debugging, 7 times; mixing up hoisting between declarations and expressions, 5 times. 19 + 17 + 15 + 14 + 12 + 11 + 7 + 5 = 100, and the books balance.
After writing the order page's function logic, run through these seven questions before launch. First, are calls and definitions apart in your mind? A name plus parentheses is a call; a bare name is passing a function, and one extra pair of parentheses in a callback makes the function run early. Second, do the argument count and order match? Too few becomes undefined, too many are ignored, and a wrong order computes the bill wrong. Third, are the default-value conditions right? A default only steps in when nothing is passed or undefined is passed; an empty string and 0 do not trigger it. Fourth, is the rest parameter last? A function can have only one rest parameter, it cannot have a default value, and no comma may follow it. Fifth, are arrow functions in the right place? Use ordinary functions for methods, constructors, and anywhere "this" must mean the object itself; use arrow functions for short callbacks and when you want to keep the outer "this". Sixth, did you write return? If the caller needs a value back, return is required; without it the caller gets undefined. Seventh, did you check variable scope? Variables inside a function are invisible outside it, and a ReferenceError should send you to check scope first, not to make the variable global. After these seven questions, look back at the three MDN documents: the Learn article covers the basic ideas of functions and scope, the Arrow function expressions reference is the complete manual for arrow functions, and the Rest parameters reference is the rule list for rest parameters. They have different jobs, so do not go to the wrong one when you have a question: for whether a particular form is allowed, go to the matching reference; for how functions fit together overall, go back to the Learn article. One last reminder: generator functions, the details of arrow functions inside async functions, and decorators, none of which this guide covers, each have their own traps. When you really need them, read the matching MDN document first instead of writing from memory.
Comments (0)
Sources
Related articles
Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.
A selector is the first part of a rule: it decides who the styles land on. This guide follows MDN's Basic CSS selectors, Attribute selectors, and Pseudo-classes and pseudo-elements: type, class, ID, selector lists, universal, attribute selectors, pseudo-classes, pseudo-elements, chaining them together, plus a checklist for when a style does not show up.
No image files, no library: the order page's weekly bar chart and smiley face are drawn live with Canvas. This guide follows MDN's Canvas tutorial — Basic usage, Drawing shapes, and Applying styles and colors: the 300×150 default, the top-left origin, fillRect and strokeRect, the beginPath-moveTo-lineTo-fill/stroke path pattern, arcs in radians, Bezier curves, fillStyle and strokeStyle, transparency, line styles, gradients, patterns, shadows, and redrawing for motion.