First-Class Functions

Assign Function to a Variable

We can create a function that will return something, then after we can assign that function to a variable. As shown below.

const sayBye = () => {
return 'Goodbye my friend';
// "Goodbye my friend"

Function Passed as an Argument

We will use the previous example to pass as an argument in another function.

const sayByeToFriend = (greeter, friend) => {
return greeter() + ' ' + friend;
console.log(sayByeToFriend(sayBye, 'Steve'));
// Goodbye my friend Steve

Returning a Function From Another Function

We can also return a function, I will use the previous example to show how we can change what is said, I will show you how.

const goodbyeMaker = greeting => {
return friend => {
return greeting + ' ' + friend;
const sayByeToFriend = greeterMaker('Bye');
const sayAdiosToFriend = greeterMaker('Howdy');
// "Goodbye my friend Jane"
// "Adios mi amigo Same"

Object Validation

Lets say that we have a lot of information for an object that is needed to pass to be a valid object. We can make a function that will iterate over the criteria and return to us if the object is valid or invalid.

const isUsernameLong = obj => {
return obj.username.length >= 8;
const arePasswordSame= obj => {
return obj.password === obj.confirmPassword;
//Function to check valid or not
const objectIsValid = (obj, ...funcs) => {
for (let i = 0; i < funcs.length; i++) {
if (funcs[i](obj) === false) {
return false;
return true;
const obj1 = {
username: 'ahmed123',
password: 'welcome',
confirmPassword: 'welcome',
const obj1Valid = objectIsValid(obj1, usernameLongEnough, passwordsMatch);
// true
const obj2 = {
username: 'habibi',
password: 'hello',
confirmPassword: 'hello',
const obj2Valid = objectIsValid(obj2, usernameLongEnough, passwordsMatch);
// false


I hope this helped as with everything you need some practice to really grasp the concept. But first-class functions in JavaScript can be really useful tool in conjuction with the other types of functions. I hope this has been helpful.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store