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.
Recommended Posts
View AllTop 10 ES6 Features Every JavaScript Developer Must Know
The specification for JavaScript implementation is provided by ES6. Learn about its recently added ES6 features that make writing JavaScript easier!
What is the let keyword in JavaScript?
Learn all about the let keyword in JavaScript and how it differs from var. Explore its scope, hoisting, and best practices for usage.
What is the difference between Call, Apply and Bind
Looking to learn about the differences between Call, Apply, and Bind in JavaScript? This article breaks down the nuances of each method and provides c...
What is currying function in JavaScript ?
Currying function in JavaScript allows you to transform a function that takes multiple arguments into a series of functions that each take one arg.
How do you decode or encode a URL in JavaScript?
Learn how to encode and decode URLs in JavaScript with this comprehensive guide. Avoid common mistakes and ensure data security. Read more now.