JavaScript functions
Functions organize a bunch of statements into chunks that we can edit easily and re-use in different places:
function doStuff(passedInVariable1, passedInVariable2, ...) {
let task1 = passedInVariable1
let task2 = passedInVariable2
// and so on and so on
const addendum1 = 'and sleep'
const addendum2 = 'and work'
task1 += ' ' + addendum1
task2 += ' ' + addendum2
const returnPhrase = task1 + ' then ' + task2
console.log(returnPhrase)
return returnPhrase
}
Function parameters
In JavaScript, we can pass input called parameters (passedInVariable1, passedInVariable2, etc. in the above example) into functions, and the output will adjust according to the input.
We would pass the parameters in by calling (using) the functions like this:
doStuff('eat dinner', 'eat breakfast')
// eat dinner and sleep then eat breakfast and work
doStuff('do homework', 'take the bus')
// do homework and sleep then take the bus and work
Functions encapsulate code into chunks. So, unlike HTML and CSS, JavaScript code can look "non-linear" to anyone coming from a background of only HTML and CSS. Most "real" programming actually works this way:
- write some related statements that do one thing
- put them into a capsule called a "function"
- call (use) these functions in any part of the program that require them
- this can mean calling functions anywhere in the code
The return keyword
Inside the function doStuff
we saw this return
keyword that does this:
- When we make a call to the function
doStuff
, the call yields areturn
value - If we assign that function call into a variable, the variable would hold that
return
value (and not the function itself)
const regime = doStuff('eat dinner', 'eat breakfast')
console.log(regime)
// eat dinner and sleep then eat breakfast and work
However, we can also assign the entire function into a variable:
const regime = doStuff
Then, we would be storing the function itself (and not the function call) into the variable! We could then call the function using the variable:
regime('eat dinner', 'eat breakfast')
// eat dinner and sleep then eat breakfast and work
Functions with default values in parameters
Sometimes, we can have functions with optional parameters, by setting default values into them, when passing the parameter:
const doStuff = (param1, param2 = "sleep") => {
return param1 + ' then ' + param2
}
console.log(doStuff("eat", "watch TV"))
// eat then watch TV
console.log(doStuff("eat"))
// eat then sleep
The optional parameter in the sample above is param2
which defaults to "sleep" if the function call does not give a second argument for param2
!