DEVELOPMENT
JAVASCRIPT
JavaScript Fundamentals: First Class Functions
Functions are known as first class citizens in JavaScript, here's exactly what that means.
Functions are First Class Citizens
- Meaning you can treat functions like any other variable in the language.
- For example, you can pass a function as an argument to another function or a function can be returned by another function and assigned to a variable.
Storing a function in a variable.
const example = () => {
console.log('This is an example')
}
Invoking the function by using the variable it was stored in.
example()
Passing a function as a variable
function sayName() {
return 'Coner'
}
function shout(text) {
return text.toUpperCase()
}
We call
`sayName()`
which returns ‘Coner’ this is then immediately passed to shout() which returns it in the upper case.
console.log(shout(sayName()))
Returing a function
If we want to invoke the function returned from another function we have a couple of options:
Option 1
const sayName = function () {
return function () {
console.log('Coner')
}
}
But, directly invoking our function doesn’t yeild the result we wanted.
sayName() // Doesn't return 'Coner' instead directly returns the function.
To achieve the result we want of logging out ‘Coner’, we have store our function into another variable and invoke that.
const func = sayName()
func() // 'Coner'
Option 2
const sayName = function () {
return function () {
console.log('Coner')
}
}
If we want to avoid using the variable method shown above we can use the double parentheses method to invoke the parent function and then the child function it returns which gives us the result we were after.
sayName()() // 'Coner'