# Function Declaration vs Function Expression

**Functions**\-  
functions enclose a piece of code within them that perform a certain task.  
They provide us with the following :-

*   Enclose a block of code inside a reusable unit
    
*   Keep code cleaner and organized
    
*   Avoid repetition (DRY principle – Don’t Repeat Yourself)
    
*   Improve readability and maintainability
    
*   Reuse logic multiple times
    

**Write once , use many times**

* * *

**Function declaration**

A function declaration defines a **named function** using the `function` keyword.

```javascript
function getSum(a, b) {
  console.log("sum: " + (a + b));
}

getSum(2, 4);  // function call
```

*   `getSum` is the **function name**
    
*   `a` and `b` are **parameters** (inputs to the function)
    
*   `{}` contains the block of code that runs when the function is called
    
*   `getSum(2, 4)` is the **function call**, where `2` and `4` are arguments
    

**Returning a value**

Instead of just printing the result, we can return it using the `return` keyword.

```javascript
function getSum(a, b) {
  return a + b;
}

const sum = getSum(2, 4);
console.log(sum);  // 6
```

*   `return` sends the result back to where the function was called
    
*   It allows us to store the result in a variable
    
*   The function stops executing once `return` runs
    
*   `sum` will hold the value `returned` by `getSum` function.
    

**Function Expression**

A function expression stores a function inside a variable.

```javascript
const addition = function getSum(a, b) {
  return a + b;
}

getSum();
```

Here:

*   The function is assigned to a variable
    
*   The variable name is used to call the function
    

**Difference between declaration and expression**

**Hoisting** -  
**Declaration syntax** - The declaration syntax gets hoisted i.e the function can be called even before its declared, **lifted** by javascript to the top of the file before running.

**Expression syntax (NOT Hoisted)** - since in this syntax , the function will be held inside a variable. It won't be executed until execution reaches that line

```javascript
// declaration
sayHi();  // works
function sayHi() { console.log("Hi!"); }

// expression
sayBye(); // crash
const sayBye = function() { console.log("Bye!"); };
```

<table style="min-width: 50px;"><colgroup><col style="min-width: 25px;"><col style="min-width: 25px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p></p></td><td colspan="1" rowspan="1"><p><strong>Usage</strong></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Declaration</strong></p></td><td colspan="1" rowspan="1"><p>want a global function that can be used anywhere</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Expression</strong></p></td><td colspan="1" rowspan="1"><p>want to keep code structured, scoped, or passed into other functions.</p></td></tr></tbody></table>
