Function Statements vs Function Expressions in JavaScript.
Functions are the heart of JavaScript and we all have worked with functions in JavaScript but we always stay confused if someone asked the difference between Function Statement and Function Expression.
Let’s start with their definitions —
Function Statements- A Function Statement is a way to define a named function using the
functionkeyword. It creates a reusable block of code that can be called anywhere in the program. These are also known as Function Declarations. For example-
function greet() {
console.log("Hello, Learners!");
}
greet(); // Output: Hello, Learners! Function Expressions — A Function Expression is a function assigned to a variable. It can be either named or anonymous (functions which do not have name) and is often used in callbacks and higher-order functions. For example-
const greet = function() {
console.log("Hello, world!");
};
greet(); // Output: Hello, world!At first glance, both examples look similar, what’s the difference between them?
Get Nikunjvar’s stories in your inbox
Join Medium for free to get updates from this writer.
The key difference is Hoisting.
Function Statements are hoisted, meaning they can be called before their definition.
Function Expressions are not hoisted, so calling them before declaration results in an error.
If we try calling a Function Expression before defining it, JavaScript will throw a ReferenceError.
Other common key difference between Function Statements vs Function Expressions is Naming. Function Statements must have a name, while Function Expressions can be anonymous.


