> For the complete documentation index, see [llms.txt](https://javascript-1.gitbook.io/javascript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://javascript-1.gitbook.io/javascript/first-class-function.md).

# First-class function

A function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.

### Assign a function to a variable: <a href="#example_assign_a_function_to_a_variable" id="example_assign_a_function_to_a_variable"></a>

```javascript
const foo = function() {
   console.log("foobar");
}
// Invoke it using the variable
foo();
```

&#x20;We assigned an `Anonymous Function` in a `Variable`, then we used that variable to invoke the function by adding parentheses `()` at the end.

### Pass a function as an Argument: <a href="#example_pass_a_function_as_an_argument" id="example_pass_a_function_as_an_argument"></a>

```javascript
function sayHello() {
   return "Hello, ";
}
function greeting(helloMessage, name) {
  console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!");
```

&#x20;We are passing our `sayHello()` function as an argument to the `greeting()` function, this explains how we are treating the function as a `value`.

### Return a function: <a href="#example_return_a_function" id="example_return_a_function"></a>

```javascript
function sayHello() {
   return function() {
      console.log("Hello!");
   }
}
```

&#x20;We need to return a function from another function - *We can return a function because we treated function in JavaScript as a `value`.*
