Learn JavaScript
❯ functions.functions_basics

Defining and Calling Functions in JavaScript

$concept

Functions package reusable logic under a name, declared with function add(a, b) or as expressions (const add = function...). Calling runs the body with arguments bound to parameters, then resumes after the call β€” missing arguments arrive as undefined, extras are ignored (available via rest). Return values hand results back; falling off the end returns undefined.

JavaScript functions are first-class values: assignable, passable, returnable β€” the foundation of callbacks, higher-order functions, and functional patterns throughout the language.

$how it works
1

Declaration anatomy

function add(a, b) { return a + b; } β€” name, parameters, body; return hands a value back.

2

Call and resume

add(2, 3) binds a=2, b=3, computes, and returns 5 to the call site expression.

3

Missing means undefined

add(2) leaves b undefined (NaN on use) β€” arity is never enforced, only conventional.

4

First-class values

Functions assign to variables and pass as arguments β€” the gateway to callbacks and composition.

$example
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
Output
5
1The declaration defines add before the call (hoisted, so order wouldn't matter).
2add(2, 3) computes 2 + 3 and returns 5.
3The returned value flows into console.log and prints.
$use cases
Decomposing scripts into named, testable helpers
Reusing validation and formatting logic across call sites
Passing behavior as arguments (callbacks begin here)
Returning early with guard clauses inside function bodies

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.