What do you mean by "Functions are the first class citizens" of Javascript?
Haha! I've had the similar reaction when I heard it the first time - "Functions are the first class citizen of Javascript." Even today, I see the similar reactions from folks learning Javascript!
Let me try to simplify this a bit.
In Javascript world, string, numbers, boolean, even objects and arrays, they all are first class citizens! Well, now you'll say I'm explaining a jargon using a jargon, how does that simplify the concept. I agree... Patience!
What makes them first-class? - You can pass them around, store them in variables and arrays, can do some calculations on those datasets and can be used as any piece of data. Hence, they're being referred as First class.
Wait! Do you mean, functions can also be treated same and hence in turn called as First class? You got it. Functions can be data too. That's what make JS a functional programming language. Talk is cheap, show me the code. ;p
Just like other datatypes,
- You can store functions in variables
let addTwoNumbers = (a,b) => a+b;
- You can pass them around to other functions
let double = (numberArray) => { reutrn numberArray.map((eachNumber) => eachNumber * 2); }
- You can return functions from other functions
function makeFunc() { let alertMessage = 'JS is awesome!'; function displayAlertMessage() { alert(alertMessage); } return displayAlertMessage; } makeFunc()();
- You can store functions in arrays and objects
let functionArray = [function(){....}, function(){....}, function(){....}]; let functionObject = { f1: function() { doSomething }, f2: function() { doSomethingElse }, f3: function() { doSomethingDifferent } }
Javascript treats Functions the same way! That makes, functions are eligible to operate on other functions, which also make them Higher Order Functions!
Functions are just awesome. After all, that's how we, humans think. In abstractions! You visit a coffee shop, you simply ask for a cup of cappuccino, you don't need to tell a coffee maker algorithm/steps to make you cappuccino. That's what functions essentially do for you, simplify your life!
Hope that clears some clutter. Stay tuned for more on Functional Programming in Javascript.