First-Class Citizens’ means that functions can be used in the same way as other data types. It implies that functions can be assigned to variables, passed as arguments to other functions, and returned as values. This is a crucial concept in functional programming as it allows us to write more modular and reusable code.
Here are some examples of using functions as first-class citizens in JavaScript:
const add = function(x, y) { return x y; } console.log(add(5, 4)); // Output: 9 console.log(typeof(add)); // Output: function
function greet(name, callback) { const message = "Hello, " name "!"; callback(message); } function logMessage(message) { console.log(message); // Logs "Hello, Nozibul!" } greet("Nozibul", logMessage); // Logs "Hello, Nozibul!"
function add(x) { return function(y) { return x y; }; } const addFive = add(5); console.log(addFive(3)); // Output: 8
function add(a, b) { return a b; } var arr = []; arr.push(add); console.log(arr); // Output: [ [Function: add] ] console.log(arr[0](2, 5)); // Output: 7
function add(a, b) { return a b; } var obj = { sum: add }; console.log(obj.sum(5, 7)); // Output: 12 console.log(obj); // Output: { sum: [Function: add] }
These examples demonstrate how functions in JavaScript can be treated as first-class citizens, allowing for powerful functional programming paradigms.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3