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

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

Function Passed as an Argument

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

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

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.

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

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.

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

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.