JavaScript functions
grouping code into actionable chunks (the "verbs")
Functions organize a bunch of statements into chunks:
We can then call (or "invoke") them repeatedly, without having to re-write all the code inside of it:
Functions thereby allow for code re-use!
The return
keyword
return
keywordInside the aforementioned function doStuff
we saw this new return
keyword that simply means this:
When we make a call to the function
doStuff
, the call yields areturn
valueIf we put the function call into a variable, the variable holds that
return
value:
A function does not need a return
keyword but try to avoid that practice; the function would return undefined
if no return
keyword exists!
Function as an object
Functions with default values in parameters
Sometimes, we can have function with optional parameters by setting default values into them:
In the example above, param2
is an optional parameter which defaults to "sleep
" if the function call does not give an argument for param2
!
Function as a property of an object
Methods are functions that are properties of an object:
We will look objects in more detail in the next page...
Last updated