Step 1 of 7 · Reading · ~3 min
Learn
Functions
Function Declarations
A function is a named piece of code that takes inputs and gives back a result. By the end of this lesson you can write functions that return values, give parameters defaults, and build one function out of another.
Declaring and calling
The pieces: the keyword function, a name, parameters in parentheses (names for the inputs), and a body in braces. The values you pass when calling, here 10, are arguments. The call isEven(10) is itself a value: whatever the function returns.
return versus console.log
return hands a value back to the caller and ends the function immediately. console.log only writes to the screen; the caller gets nothing.
A function with no return returns undefined. The usual symptom of a forgotten return is a program that prints undefined.
Since return ends the function, you can use it to leave early and keep the rest of the code free of nesting:
Parameters and defaults
Arguments are matched to parameters by position. A missing argument becomes undefined; an extra one is ignored. A default value fills in for a missing argument:
Rest parameters
...name as the last parameter collects any number of extra arguments into a list (an array; the arrays lesson covers them):
Functions that call functions
Small functions that each do one thing can be combined. Anything a function needs from another must be reached by calling it:
Scope
Variables declared inside a function exist only inside it, and each call gets a fresh set. A function can read variables declared outside it, but the outside cannot see in:
Declarations are hoisted
A function declaration is available in the whole file, even above the line where it is written, so a program can start with the main logic and define helpers below. A function stored in a variable (const f = function() {...}) is not available until that line has run.
Functions are values
A function can be stored in a variable or passed as an argument, which is the basis for the callbacks you will meet in the array lessons:
Common mistakes
- Forgetting
return, or writingconsole.logwherereturnwas needed. - Writing code after a
returnin the same block: it never runs. - Calling
finstead off():console.log(isEven)prints the function, not a result. - Passing arguments in the wrong order; the names do not matter, only the position.
- Returning a number when the caller expects true/false (or the other way around).
Your exercise
Build a tiny calendar helper out of two functions, where one calls the other. The starter gives you both bodies empty; the program at the bottom already reads the input and prints what daysInMonth returns.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…