JavaScript Function Statements vs Function Expressions

JavaScript

JavaScript function statements and function expressions are two ways you can write a function in your JavaScript code, but what is the difference?

JavaScript is executed synchronously (line by line) however if you came across a snippet of code like this, you might think the function will not be executed because the code is executed synchronously, the invocation greet() has been placed before the function. Yet it will still run and execute the code and output Hello to the console.

Function Statements

greet();
function greet() {
   console.log('Hello');
}

If JavaScript is synchronous, why can we invoke this function above the function statement?

When JavaScript is first read by the JavaScript engine, known as the Creation Phase, it stores all function statements (which includes the entire code within the function) and variable declarations into memory before the code is run, this is known as hoisting. So by the time greet() is called during the Execution Phase, the function was already available in memory, pretty neat right?

OK, so what about this?

Function Expressions

anotherGreet();
var anotherGreet = function() {
   console.log('Hello');
};

If you run this code you will get an Uncaught TypeError: anotherGreet is not a function but why?

From the interpreters perspective, you have created a variable and assigned it a value.

During the creation phase, the variable declaration anotherGreet is stored in memory but its value is not and by default, the JavaScript engine assigns it a value of undefined.

When you try to invoke anotherGreet() above the function expression, JavaScript reads the value of the function as undefined which is as the error points out, not a function.

Further Reading:

  • JavaScript Functions MDN
Matthew Horne

Matthew is a web developer from the United Kingdom who taught himself PHP and JavaScript and never looked back. If you would like to hire me, shoot me an email.