Function by Example
Function by Example
Definition
When creating a named function, we must start with the keyword “function” followed
by the name of a function. The name of a function must always start with a
lowercase or camelCase it will be followed by a pair of parenthesis and then with a
pair of curly brackets. This function logic must be placed between the pair of curly
brackets.
function greeting() {
// Document
document.write("Hello There")
// Console
console.log("Hello There");
// label with an id of output
document.querySelector('#output').style.backgroundColor = '#B4FBA1'
document.querySelector('#output').textContent = "From code.js"
}
You must call a function for this function to execute its task.
greeting()
Benefits of using a named function
- Can be reusables
- It has a separation between a function’s implementation and invoking or
calling a function
- The program will provide a self-explanatory error message when an error
takes place.
- Support hoisting
A function without a name. It can be defined within the parenthesis, after which we
have to specify the keyword “function” followed by the pair of parenthesis but without
a name. Later on, we have to specify the pair of curly brackets.
NB: Function expression or anonymous function is not fully hoisted
.
// Example 1
let greeting = (function() {
console.log("Hello Joel");
})
greeting()
// Example 2
let addition = function(x, y) {
return x + y
}
console.log(addition(3, 2));
/*
Example 3
Immediately invoked function
*/
(
function (x) {
console.log(x**x);
}
)(2)
// Example 4
setTimeout(
function(){
console.log("After 5 second");
},
5000
)
The below example will produce an error because JS only hoists the variable after all
it was declared but not a function. Function expression doesn’t have a name.
multiplication(3, 2)
let multiplication = function(x, y) {
console.log(x * y);
}
Arrow function
((firstName)=> {
console.log(`Hello ${firstName}`);
})('Joel')
Recursive function
A function that calls itself to create a loop.
Example.
NB: There are issues with the below example; try to fix them.
FYI, I solved it; now it's your turn. Let me know how long it took you to fix it. It only
took me a minute and 10 seconds.
It has to display numbers from 1 to 10.
function repeat(limit) {
let cnt = 1
if(cnt < limit) {
console.log(cnt);
cnt++
repeat(limit--)
}
}
repeat(10)