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 All

Learn JavaScript Closures with Code Examples


Master JavaScript closures with code examples! Our comprehensive guide explains how closures work and how to use them in your code. Start learning now...

Difference Between == and === in JavaScript


Learn the Difference Between == and === in JavaScript. Discover how each operator compares values and data types, and when to use them in code.

What is a pure function in JavaScript?


Discover what a pure function is in JavaScript and why it's important. Learn how to create and use pure functions to improve your code's reliability.

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.

JavaScript Template Literals Explained


JavaScript template literals are one of JavaScript's most powerful capabilities. They enable us to generate dynamic strings without the need for conca...