# 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`.*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascript-1.gitbook.io/javascript/first-class-function.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
