Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Functions  ›  Lesson

Function Declarations and Parameters

Function Parameters 12 minA function packages code under a name you can call; parameters are labelled mailboxes filled in call order, a missing argument arrives as undefined, and a default value only fills an empty mailbox, never a real one.

Function Declarations and Parameters

In short: a function packages a block of code under a name, so you can run it again from anywhere with name(...). Parameters are the named mailboxes a function declares; arguments are what a particular call drops into them, filled in order. Give fewer arguments than parameters and the leftover mailboxes hold undefined. A default value (param = value) only fills a mailbox that's exactly undefined — it never overrides a real value, even a falsy one like 0.

shippingFee(800, 500) filling two labelled mailboxes, total = 800 and freeAbove = 500 overriding its default; a separate greet() call leaves its name mailbox empty: undefined — with a note that a default only fills an empty mailbox

A shipping fee with a configurable threshold

Parameters can have defaults, used only when a call leaves them out:

javascript

shippingFee(2500) only fills total — freeAbove stays undefined until the default 2000 steps in. Pass a second argument, and it fills that mailbox directly; the default is never consulted.

A missing argument, and an ignored extra one

Call a function with too few or too many arguments, and JavaScript doesn't complain — it just leaves gaps or drops the extras:

javascript

greet() gives name no value at all, so it's undefined, and the message prints "Hello, undefined" — no error. add(2, 3, 999) only has two parameters, so 999 is simply never read; JavaScript never enforces argument count.

The default-value trap: 0 isn't "missing"

The rule that catches people: a default only fires for undefined, not for other falsy values.

javascript

setVolume(0) passes a genuine value — 0 — so the default is skipped entirely and the function returns 0. Only a missing argument, or one explicitly passed as undefined, triggers the default. This is different from ||-based fallbacks (level || 50), which would wrongly replace a real 0 — exactly the trap from the type-casting lessons.

Quick practice

quick drill

function f(a, b) { return a; } — what does f(5) return, and what is b?

quick drill

function f(x = 10) { return x; } — what does f(0) return?

quick drill

function f(x = 10) { return x; } — what does f() return?

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainA default that never kicks in

function setVolume(level = 50) { return level; } — explain what setVolume(0) returns and why, even though 0 looks like "no value was given."