# Function Declaration vs Expression vs Arrow Function in JavaScript

## What is the difference between function types in JavaScript?

In JavaScript you can create a function in three common ways: a **function declaration**, a **function expression** and an **arrow function**. They look similar and in simple cases they behave the same, but they differ in hoisting, in how `this` works and in what you can do with them. In this post I will explain each one and show when to use which.

I will use a small `Player` example, like in my post about constructors.

## Function declaration

A declaration starts with the `function` keyword and always has a name.

```js
function greet(nickname) {
    return `Hello, ${nickname}!`;
}

console.log(greet('Neo'));
// Output: Hello, Neo!
```

The main feature is **hoisting**. JavaScript moves the whole declaration to the top of its scope before the code runs, so you can call it before the line where it is written.

```js
console.log(greet('Neo'));
// Output: Hello, Neo!

function greet(nickname) {
    return `Hello, ${nickname}!`;
}
```

## Function expression

A function expression is a function stored in a variable (or passed somewhere as a value).

```js
const greet = function (nickname) {
    return `Hello, ${nickname}!`;
};

console.log(greet('Neo'));
// Output: Hello, Neo!
```

Only the variable is hoisted, not the function. If you call it too early, you get an error.

```js
console.log(greet('Neo'));
// Output: ReferenceError: Cannot access 'greet' before initialization

const greet = function (nickname) {
    return `Hello, ${nickname}!`;
};
```

This is not a bug. It is actually safer, because your code must define a function before using it, so the order is easier to follow.

## Arrow function

Arrow functions (ES6) are a shorter way to write a function expression.

```js
const greet = (nickname) => `Hello, ${nickname}!`;

console.log(greet('Neo'));
// Output: Hello, Neo!
```

When the body is a single expression, `return` and curly braces are optional. With one parameter you can also skip the parentheses, but I prefer to keep them.

But an arrow function is not only shorter syntax. It behaves differently in a few important places.

### 1\. Arrow functions have no own `this`

A normal function gets its own `this` depending on **how it is called**. An arrow function takes `this` from the place where it was **created**.

```js
const player = {
    nickname: 'Neo',
    startTimers() {
        setTimeout(function () {
            console.log(this.nickname);
        }, 100);
        // Output: undefined (this is not the player here)

        setTimeout(() => {
            console.log(this.nickname);
        }, 100);
        // Output: Neo
    },
};

player.startTimers();
```

This is the biggest reason arrow functions are popular for callbacks.

The other side of the coin: do not use an arrow function as an object method.

```js
const player = {
    nickname: 'Neo',
    sayName: () => console.log(this.nickname),
};

player.sayName();
// Output: undefined (or an error in ES modules), because this is NOT the player
```

### 2\. Arrow functions have no `arguments` object

```js
function sumOld() {
    return Array.from(arguments).reduce((a, b) => a + b, 0);
}

const sumNew = (...numbers) => numbers.reduce((a, b) => a + b, 0);

console.log(sumOld(1, 2, 3)); // Output: 6
console.log(sumNew(1, 2, 3)); // Output: 6
```

In arrow functions use rest parameters (`...numbers`). They are cleaner anyway.

### 3\. Arrow functions cannot be used as constructors

```js
const Player = (nickname) => {
    this.nickname = nickname;
};

new Player('Neo');
// Output: TypeError: Player is not a constructor
```

If you need `new`, use a regular function or a `class` (more about it in my post about constructors).

## Anonymous functions

An anonymous function is a function **without a name**. It is not a fourth type. It describes how a function is written, and function expressions and arrow functions can both be anonymous. A function declaration always needs a name.

You use them all the time, mostly as callbacks:

```js
// anonymous function expression
[1, 2, 3].map(function (n) {
    return n * 2;
});

// anonymous arrow function
[1, 2, 3].map((n) => n * 2);
```

Another classic use is an **IIFE** (Immediately Invoked Function Expression). It runs right away and keeps its variables private.

```js
(function () {
    const secret = 'hidden';
    console.log('Setup done');
})();
// Output: Setup done
```

### Is it really without a name?

Not always. When you assign an anonymous function to a variable, JavaScript uses the variable name as the function name. Passed inline, it has no name at all.

```js
const greet = function () {};
console.log(greet.name);
// Output: greet

console.log((function () {}).name);
// Output: (empty string)
```

### Why a name can be useful

A name helps in debugging, because error stack traces show it instead of `anonymous`. It also lets a function call itself. For that you can give a name to a function expression. This is called a **named function expression**, and the name is visible only inside the function.

```js
const countdown = function count(n) {
    if (n === 0) return 'Done';
    return count(n - 1);
};

console.log(countdown(3));
// Output: Done

console.log(typeof count);
// Output: undefined
```

A good rule: anonymous is fine for short, one-time callbacks. If the function is long, reused, or hard to debug, give it a name.

## Quick comparison

|  | Declaration | Expression | Arrow |
| --- | --- | --- | --- |
| Hoisted with its body | Yes | No | No |
| Own `this` | Yes | Yes | No (takes it from outside) |
| `arguments` object | Yes | Yes | No |
| Can be used with `new` | Yes | Yes | No |
| Needs a name | Yes | No | No |
| Short syntax | No | No | Yes |

## Which one should I use?

There is no single right answer, but this rule of thumb works well in most projects:

- **Arrow function** for callbacks and short helpers, for example `array.map(...)`, `filter`, `setTimeout`, Promise chains, and inside classes when you need to keep `this`.
- **Function declaration** for top-level, named functions that are the main building blocks of a file. Hoisting lets you put the important code first and the helpers below.
- **Function expression** when you need to pick a function conditionally, or when you want a function to be defined only after a certain line.
- **Method shorthand** (`sayName() {}`) for methods inside objects and classes, not an arrow function.

## Other kinds of functions worth knowing

The three types above describe **how a function is written**. There are also types that describe **what a function does**:

- **Callback**: a function passed to another function to be called later, for example `button.addEventListener('click', handler)`.
- **Higher-order function**: a function that takes another function as an argument or returns one, like `map`, `filter` and `reduce`.
- **Pure function**: always returns the same result for the same arguments and changes nothing outside. It is easy to test and a good default.
- **Async function**: marked with `async`, always returns a Promise and lets you use `await`.
- **IIFE** (Immediately Invoked Function Expression): runs right where it is defined, often to create a private scope.

```js
const double = (n) => n * 2;          // pure function
const numbers = [1, 2, 3].map(double); // higher-order function + callback
console.log(numbers);
// Output: [2, 4, 6]
```

I will explain each of them in a separate post.

## Summary

Declarations are hoisted and good for main named functions. Expressions give you more control over when a function exists. Arrow functions are short and keep `this` from the outer scope, which makes them perfect for callbacks but wrong for methods and constructors. Knowing these differences helps you avoid the most common `this` bugs and write more predictable code.
