JavaScript functions
grouping code into actionable chunks (the "verbs")

The function
A function organizes a bunch of statements into more manageable chunks:
function doStuff(passedInVariable1, passedInVariable2, ...) {
let task1 = passedInVariable1
let task2 = passedInVariable2
const addendum1 = 'and then go to sleep'
const addendum2 = 'and then go to work'
task1 += ' ' + addendum1
task2 += ' ' + addendum2
return task1 + ', then later: ' + task2
}
We can then call them again and again without having to re-write all the code in the function:
console.log(doStuff('eat dinner', 'eat breakfast'))
/*
eat dinner and then go to sleep,
then later: eat breakfast and go to work
*/
console.log(doStuff('take a bath', 'skip breakfast'))
/*
take a bath and then go to sleep,
then later: skip breakfast and go to work
*/
So, functions provide a powerful mechanism for code re-use!
The return keyword
Inside the aforementioned function, doStuff , we see this return keyword which simply means this:
- When we make a call to
doStuff, the call provides itsreturnvalue
We can put a function call into a variable, in this case, with regime:
function doStuff(passedInVariable1, passedInVariable2, ...) {
let task1 = passedInVariable1
let task2 = passedInVariable2
const addendum1 = 'and then go to sleep'
const addendum2 = 'and then go to work'
task1 += ' ' + addendum1
task2 += ' ' + addendum2
return task1 + ', then later: ' + task2
}
const regime = doStuff('eat dinner', 'eat breakfast')
console.log(regime)
/*
eat dinner and then go to sleep,
then later: eat breakfast and go to work
*/
When we use console.log on the variable regime, the console will output a version of the return statement, depending on the inputs!
A function does not need a return statement but it sure helps to have one :)
Function as an object
A newer way to write a function:
// ES6+ shorthand ("fat arrow notation")
const doStuff = (task1, task2) => {
// function content
}
// or without shorthand
const doStuff2 = function(task1, task2) => {
// function content
}
// or (older way)
const doStuff3 = function(task1, task2) {
// function content
}
The "fat-arrow" (=>) notation differes from the older notation and we will discuss this in a future article!
Function as a property of an object
Methods are functions that are properties of an object:
const myObject = {
someKey: "someValue",
doStuff: function() {
// function content - no declaration keyword required
}
}
We will look objects in more detail in a future article!



