First-Class Functions

In JavaScript you have the use of first-class functions, you may be asking yourself what a first-class function is. They are functions that may be treated as other values. They can may be assigned to variables, passed as arguments in other functions, and can be returned from other functions. We will take a look at each of these types of functionality.

Assign Function to a Variable

const sayBye = () => {
return 'Goodbye my friend';
};
console.log(sayBye());
// "Goodbye my friend"

Function Passed as an Argument

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

To explain what happened we pass sayBye function to sayByeToFriend function. When inside the sayByeToFriend function we will now point to sayBye, which is stored in memory. When we call greeter(), we call the function.

Returning a Function From Another Function

const goodbyeMaker = greeting => {
return friend => {
return greeting + ' ' + friend;
};
};
const sayByeToFriend = greeterMaker('Bye');
const sayAdiosToFriend = greeterMaker('Howdy');
console.log(sayHelloToPerson('Jane'));
// "Goodbye my friend Jane"
console.log(sayAdiosTof=Friend('Sam'));
// "Adios mi amigo Same"

As you can see by changing the argument you can change the name of ther person. You can also return the greeting you specify.

Object Validation

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);
console.log(obj1Valid);
// true
const obj2 = {
username: 'habibi',
password: 'hello',
confirmPassword: 'hello',
};
const obj2Valid = objectIsValid(obj2, usernameLongEnough, passwordsMatch);
console.log(obj2Valid);
// false

As you see in example one both username and password pass the conditions so we see it is true when we validate. For object two although the passwords match the username is not long enough, so it is false. We can see how this could come in handy so we do not need to manually check each user one by one.

Conclusion

--

--

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