If functions in a programming language are treated similarly to other variables, the language is said to have first-class functions. Therefore, the functions can be returned by another function, assigned to any other variable, or supplied as an argument. Functions are treated as first-class citizens in JavaScript. This implies that functions are just another sort of object and are nothing more than values.
Let’s use an illustration to learn more about the first-class function.
<script>
const codesolutionstuff = {
add: (x, y) => {
return `${x} + ${y} = ${x + y}`;
},
subtract: (x, y) => {
return `${x} - ${y} = ${x - y}`
},
multiply: (x, y) => {
return `${x} * ${y} = ${x * y}`
},
division: (x, y) => {
if (y != 0) return `${x} / ${y} = ${x / y}`;
return `Cannot Divide by Zero!!!`;
}
}
document.write(codesolutionstuff.add(200, 200) + "<br>");
document.write(codesolutionstuff.subtract(100, 7) + "<br>");
document.write(codesolutionstuff.multiply(50, 50) + "<br>");
document.write(codesolutionstuff.division(100, 5));
</script>
Output:
200 + 200 = 400 100 - 7 = 93 50 * 50 = 2500 100 / 5 = 20
Example 2:
<script>
const codesolutionstuff = (x, y) => {
return (x + " " + y);
}
document.write(codesolutionstuff("Shailesh", "Coder"));
</script>
Output:
Shailesh Coder
First class functions are what it’s all about, and we’ve better explained how they’re used and implemented.