cover
JavaScriptInterviewFunction

First Class Function in JavaScript

Summary
Hello friends. In today's post, we'll go into detail about another important concept in JavaScript that plays a crucial role First Class Functions!
Category
JavaScript
Interview
Function
Cover
https://utfs.io/f/382dfc46-f3b2-47c6-b2b7-1dbb2137f3e7-mec7yi.png
Slug
javascript-first-class-function
Date
author
Published
Published
Almost everyone knows what a function is, and you can do a lot with functions!
A simple function:
function sayHello(){ console.log("Hello") } sayHello() // Hello
So, what exactly is a First class function?
In short, the ability to assign a function to a variable, use a function as an argument for another function, or return a function from any block is an example of a First class function.
Let's understand it better through examples!
  1. Storing in a variable: Functions can be stored in a variable.
    1. let func = function() { return "Hello!"; };
  1. Returning as a result: Functions can be returned as a result from other functions.
    1. function returnFunc() { return function() { return "Returned function!"; }; } let newFunc = returnFunc(); console.log(newFunc());
      In our code, a function is returned within returnFunc, and we assigned it to a variable named newFunc by calling returnFunc(). Notice that () is used to invoke a function. In the last line, we call the returned function again using the newFunc() variable.
      You can also call the returned function directly without assigning it to a variable by using double parentheses like returnFunc()().
  1. Passing as an argument: Functions can be passed as arguments to other functions.
    1. function sayHello() { return "Hello "; } function greet(hiFunc, name){ console.log(hiFunc() + name); } greet(sayHello, "Ali");
      As you can see in the code, the sayHello() function returns the word "Hello".
      The greet() function accepts hiFunc as a function for the first argument and name as a string for the second argument.
      Notice that we passed the sayHello() function as the first argument to the greet() function in the last line, which is exactly the scenario where the First class function concept applies. The second argument is a string.
      💡
      Be careful when working with these () parentheses. If you call the function with parentheses like greet(sayHello(), "Ali"); it will cause an error because the returned internal function won't be invoked!
 
Now we know what a First class function is. 😎
I hope the article was helpful! Thank you for your attention.
 
Back

Similar Articles

Anvarbek Dev © 2024 All rights reserved.