An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
January 20, 2022 05:46 pm GMT
Original Link: https://dev.to/pranav016/advanced-javascript-series-part-7-first-class-citizens-higher-order-functions-3cda
Advanced JavaScript Series - Part 7: First Class Citizens & Higher Order Functions
First Class Citizens
First-class citizenship simply means being able to do what everyone else can do. In JavaScript, functions are objects (hence the designation of first-class object).
JavaScript has all those abilities or features that are required to be a language having First Class Functions, hence functions are treated as First Class Citizens.
Lets look at all the abilities of functions being a First Class Citizen.
1. Ability to treat functions as values-
Code-
var hello = function(){ return "hello world"}console.log(hello())
Output-
"hello world"
2. Ability to Pass functions as arguments-
Code-
function hello(fn){ fn()}hello(function() { console.log("hello world") })
Output-
"hello world"
3. Ability return a function from another function-
Code-
function hello(){ return function() { return "hello world" }}var hi=hello()console.log(hi())
Output-
"hello world"
- Because this behavior of JS functions as first class citizens, we are also able to do functional programming that we will learn more about in further parts of our series.
Higher Order Functions-
A higher order function is a function that takes a function as an argument, or returns a function.
Simplified Example-
Code-
const multiplyBy = (num1) => { return function (num2) { return num1 * num2; }}const multiplyByTwo = multiplyBy(2);multiplyByTwo(4)
Output-
8
Connect with me-
Appendix-
- Advanced JavaScript Series - Part 1: Behind the scenes (JavaScript Engine, ATS, Hidden Classes, Garbage Collection)
- Advanced JavaScript Series - Part 2: Execution Context and Call Stack
- Advanced JavaScript Series - Part 3: Weird JS behavior, Strict Mode and Hoisting, Temporal Dead Zone
- Advanced JavaScript Series - Part 4.1: Global, Function and Block Scope, Lexical vs Dynamic Scoping
- Advanced JavaScript Series - Part 4.2: Scope Chains and their working, Lexical and Variable Environments
- Advanced JavaScript Series - Part 5: IIFE & 'this' keyword in JS(tricky Eg.), call(), apply(), bind(), Currying(Functional Prog)
- Advanced JavaScript Series - Part 6.1: Everything in JS is an Object? Weird JS behaviors revealed, Primitive Non-Primitive Types
- Advanced JavaScript Series - Part 6.2: Pass by Value & Pass by Reference, Shallow & Deep Copy, Type Coercion
References-
Original Link: https://dev.to/pranav016/advanced-javascript-series-part-7-first-class-citizens-higher-order-functions-3cda
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To