Skip to content
Function Declarations
step 1/7

Reading — step 1 of 7

Learn

~2 min readFunctions

Functions are reusable blocks of code that take inputs (parameters) and return an output. Three reasons to write a function: reuse (call it many times), abstraction (give a meaningful name to a multi-step operation), and isolation (variables inside don't leak out).

Function declaration

js

Four pieces:

  1. The function keyword.
  2. The function name (camelCase, descriptive).
  3. Parameters in parens — local names that receive values when called.
  4. A { ... } body — usually with a return statement.

Function expressions — assign to a variable

js

Functions are FIRST-CLASS values in JavaScript: you can store them in variables, pass them as arguments, return them. Both forms work; the difference is hoisting:

  • Function declarations are hoisted — usable BEFORE the declaration line.
  • Function expressions are not — using them before assignment raises ReferenceError.

Parameters and arguments

js

Missing arguments default to undefined. Extra arguments are silently ignored. Use default parameters to be explicit:

js

Rest parameters — variable-length args

js

...nums collects all remaining arguments into an array.

Spread at the call site

js

Same ... syntax — but at a call, it UNPACKS an array into separate arguments.

Implicit return of undefined

js

Without an explicit return, the function returns undefined. Don't confuse console.log (output) with return (the function's value).

Common mistakes

  • Forgetting return — function silently returns undefined.
  • Calling without parens: console.log(greet) logs the function itself, not its result.
  • Modifying a passed object thinking it's a copy — objects are passed by reference. Mutating one inside changes the caller's.
  • Missing default paramsfunction f(x) called with f() makes x = undefined.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…