Reading — step 1 of 7
Learn
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
Four pieces:
- The
functionkeyword. - The function name (camelCase, descriptive).
- Parameters in parens — local names that receive values when called.
- A
{ ... }body — usually with areturnstatement.
Function expressions — assign to a variable
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
Missing arguments default to undefined. Extra arguments are silently ignored. Use default parameters to be explicit:
Rest parameters — variable-length args
...nums collects all remaining arguments into an array.
Spread at the call site
Same ... syntax — but at a call, it UNPACKS an array into separate arguments.
Implicit return of undefined
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 params —
function f(x)called withf()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…