JavaScript Functions as First-Class Values

🚀 𝗙𝗶𝗿𝘀𝘁 - 𝗖𝗹𝗮𝘀𝘀 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 In JavaScript, functions are first-class values. That means the language allows functions to be treated the same way as any other value. Practically, this gives us three abilities:  • assign a function to a variable  • pass a function as an argument  • return a function from another function Example:- 1. when assigned as a value const sayHi = function ()   console.log("Hi"); } => 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘄𝗵𝘆 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗲𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀, 𝗮𝗻𝗼𝗻𝘆𝗺𝗼𝘂𝘀 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀, 𝗮𝗻𝗱 𝗮𝗿𝗿𝗼𝘄 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗻𝗼𝘁 𝘀𝗽𝗲𝗰𝗶𝗮𝗹 𝗰𝗮𝘀𝗲𝘀 , 𝘁𝗵𝗲𝘆’𝗿𝗲 𝗷𝘂𝘀𝘁 𝘃𝗮𝗹𝘂𝗲𝘀. 2. function passed as an argument function executeFunc (callback) {   callback(); } executeFunc(sayHi) => 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘁𝗵𝗲 𝗳𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻 𝗳𝗼𝗿 𝗰𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀, 𝗲𝘃𝗲𝗻𝘁 𝗵𝗮𝗻𝗱𝗹𝗲𝗿𝘀, 𝗮𝗻𝗱 𝗮𝘀𝘆𝗻𝗰 𝗰𝗼𝗱𝗲. 𝗧𝗵𝗲 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗶𝘀 𝗷𝘂𝘀𝘁 𝗯𝗲𝗶𝗻𝗴 𝗽𝗮𝘀𝘀𝗲𝗱 𝗹𝗶𝗸𝗲 𝗱𝗮𝘁𝗮. 3. Returning from another function function outer() {  return function inner() {   console.log("Inner function executed");  }; } const fn = outer(); fn(); => 𝗧𝗵𝗶𝘀 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿 𝗲𝗻𝗮𝗯𝗹𝗲𝘀 𝗰𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗮𝗻𝗱 𝗵𝗶𝗴𝗵𝗲𝗿-𝗼𝗿𝗱𝗲𝗿 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 (𝗺𝗮𝗽, 𝗳𝗶𝗹𝘁𝗲𝗿, 𝗿𝗲𝗱𝘂𝗰𝗲). Most JavaScript patterns work because functions can be passed around like data. First-class functions are the rule that makes that possible. #Javascript #Functions #WebDevelopment #Frontend

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories