JavaScript supports functional programming because JavaScript functions are first-class citizens.
What is first-class citizens?
First-class citizens or as called first-class object means that functions can do the same things that variables can do.
It can be stored whether in a variable, array or object.
And that functions can be passed as an argument to the functions and be returned by the function.
for a better tracking of the following examples' output,I am using a
h4
with id equals ch3.
<div class="body" style=" height: 1000px; ">
<h1 style="color: brown; align-items: center; text-align: center;" class="mt-5">Learning react</h1>
<h4 class="display-6 text-center mt-4" id="ch3"></h4>
</div>
<script src="./ch3.js"></script>
let content = document.getElementById("ch3");
1- Store function in a variable.
We can declare functions with the var or let keyword the same way you can declare strings, numbers, or any other variables:
var log = function (msg) {
console.log(msg);
content.innerText += `\n ${msg}`;
};
log("In JavaScript functions are variables");
// In JavaScript, functions are variables
With ES6, we can write the same function using an arrow function
// using an arrow function
var log = (msg) => {
console.log(msg);
content.innerText += `\n ${msg}`;
};
log("In JavaScript functions are variables using an arrow function");
2- Store functions in objects
Since functions are variables, we can add them to objects:
// Since functions are variables, we can add them to objects:
const obj = {
msg: "adding functions to objects",
message: "They can be added to objects like variables",
log(msg) {
console.log(msg);
content.innerText += `\n ${msg}`;
},
};
obj.log(obj.msg);
obj.log(obj.message);
In the previous example we store a function in a variable called log.
3- Store functions in arrays.
We can also add functions to arrays in JavaScript
// Since functions are variables, we can add them to arrays:
const arr = [
"adding functions to arrays",
(log) => console.log(log),
"like variables",
(msg) => {console.log(msg);
content.innerText += `\n ${msg}`;
},
(test) => {
console.log(test);
content.innerText += `\n ${test}`;
},
"They can be inserted into arrays",
];
arr[4](arr[5]);
arr[1](arr[0])
arr[3](arr[2])
// They can be inserted into arrays
// like variables
4- Pass functions as arguments.
Functions can be sent to other functions as arguments.
const insideFn = logger => logger("They can be sent to other functions as arguments");
insideFn(log);
5- Return Functions by the function.
Functions can be also returned from other functions, just like variables:
const createScream = function(logger) {
// getting logger functions as a parameter
console.log('new func return');
return function(msg){
// getting a normal msg text as an argument
logger(`${msg} from return function !!!`);
}
}
Using ES6 syntax, we could describe the same createScream
const createScreamarrow = logger => message =>
logger(message.toUpperCase() + "!!!")
Top comments (0)