---
title: "Two ways of declaring functions"
description:
  "There are many ways of declaring a function. In this blog we will discuss two
  of those techniques."
canonical_url: "https://www.bigbinary.com/blog/two-ways-of-declaring-functions"
markdown_url: "https://www.bigbinary.com/blog/two-ways-of-declaring-functions.md"
---

# Two ways of declaring functions

There are many ways of declaring a function. In this blog we will discuss two of
those techniques.

- Author: Neeraj Singh
- Published: March 15, 2010
- Categories: JavaScript

All the JavaScript books I read so far do not distinguish between following two
ways of declaring a function.

```javascript
var foo = function () {};
function foo() {}
```

Thanks to [Ben](http://www.adequatelygood.com) today I learned that
[there is a difference](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting)
.

## When a var is used to declare a function then only the variable declaration gets hoisted up

```javascript
function test() {
  foo();
  var foo = function () {
    console.log("foo");
  };
}
test();
```

Above code is same as one given below.

```javascript
function test() {
  var foo;
  foo();
  foo = function () {
    console.log("foo");
  };
}
test();
```

## When a function variable is declared without var then both variable declaration and body gets hoisted up

```javascript
function test() {
  foo();
  function foo() {
    console.log("foo");
  }
}
test();
```

Above code is same as one given below.

```javascript
function test() {
  var foo;
  foo = function () {};
  console.log(foo());
}
test();
```

## Conclusion

Now it will be clear why `foo()` does not work in the following case while
`bar()` does work.

```javascript
function test() {
  foo(); // TypeError "foo is not a function"
  bar(); // "this will run!"
  var foo = function () {
    // function expression assigned to local variable 'foo'
    alert("this won't run!");
  };
  function bar() {
    // function declaration, given the name 'bar'
    alert("this will run!");
  }
}
test();
```

## Links

- [Human page](https://www.bigbinary.com/blog/two-ways-of-declaring-functions)
