JavaScript – Function Declarations vs. Function Expressions

Tags: javascript
Published: 2021-07-13 20:31:30

<!-- wp:paragraph {"fontSize":"small"} -->
<p class="has-small-font-size">What are the differences between function declarations and function expressions? We'll find out in this article.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We know how to write functions in JS, right? We use the <code>function</code> keyword, whose main role is to create a function. But did you know that there are two function form variants (or more, depending on the context)? If not, take a look at the code snippet below and try to understand the syntactical and logical differences.</p>
<!-- /wp:paragraph -->

```javascript
function calculateSomethingForMePlease() {
 // here goes logic - function declaration
}
let findTheClosestBeachNearMe = function(lat, lng) {
 // here goes logic - function expression
}
```

<!-- wp:heading -->
<h2>Function Declaration</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The first variant is called the <em>function declaration</em> because it is an expression by itself. We write the JavaScript keyword <em><code>function</code></em> followed by the name of the function. The parser then associates the <code>function</code> keyword with the name of the function during the compilation phase. Why is this useful? Well, we can call the function not only after the declaration but also before the declaration!</p>
<!-- /wp:paragraph -->

```javascript
calculateSomethingForMePlease(); // this is valid in JS

function calculateSomethingForMePlease() {
 // here goes logic
}
```

<!-- wp:paragraph -->
<p>In most other programming languages this doesn't work, but JS has this cool concept called <em>hoisting</em>, during which it grabs the whole function objects, and makes them available anywhere in our file by pushing it to the top, compared to the (SPOILER ALERT) the next variant that we will see.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Function Expression</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The function expression is a function that is assigned to a certain variable. As you might have guessed - the function itself is not available nor associated to the variable until the statement line has been reached during execution.</p>
<!-- /wp:paragraph -->

```javascript
findTheClosestBeachNearMe(43.94151, 17.4194); // OH NO, HELL BREAKS LOOSE!

let findTheClosestBeachNearMe = function(lat, lng) {
 // here goes logic - function expression
}
```

<!-- wp:heading -->
<h2>Function Declaration vs. Function Expression</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>So we might ask ourselves - when can we use one or the other?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As seen above - we might use<em> function declarations</em> to create standalone functions, that are visible before any other code. (compared to <em>function expression</em>s which are only visible when the interpreter reaches the line of code).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Otherwise - we might be inclined to keep our global scope clean (due to hoisting declarations can pollute the global namespace). Then we would use IIFEs (Immediately invoked Function Expressions, quite a name huh?).</p>
<!-- /wp:paragraph -->

```javascript
(function (bar){
  //Here we have an encapsulated local scope and the ability to return things
  return 'baz'
})('foo')
```

<!-- wp:paragraph -->
<p>If you've ever worked with asynchronous code, you've might also come across callbacks which are another form of <em>function expressions</em>.</p>
<!-- /wp:paragraph -->

```javascript
asyncFn(function (){
  console.log('Done!')
})
```

<!-- wp:paragraph -->
<p>Yet another form of <em>function expression</em> is the named functions inside objects. Look below for an example:</p>
<!-- /wp:paragraph -->

```javascript
const earth = {
  population: '7.674 billion',
  getPopulation: function() {
    return this.population;
  }
};
```

<!-- wp:heading -->
<h2>Final Words</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As you can see - there are more differences between the two forms than just structural, and each can fit a certain use case better. Read up on this Stack Overflow <a href="https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname" target="_blank" rel="noreferrer noopener">question</a> for additional examples and discussion regarding performance, mutability and availability.</p>
<!-- /wp:paragraph -->
<!-- /wp:paragraph -->