Function Statements Vs Function Expression

Rakesh Kumar Shaw
2 min readDec 15, 2020

Often, JavaScript developers are found encountering the above question in their interviews. Let me tell you, both are ways to create functions, and looks the same. There is a slight difference in them. Let’s understand the difference to have a clear picture of the 2 terminologies.

Function Statement — When we write a function with function keyword along with the specified parameters with requiring a variable assignment, it’s called function statement. They exist on their own, i.e, they are standalone constructs and cannot be nested within a non-function block.

Function Expression — A Function Expression works just like a function declaration or a function statement, the only difference is that a function name is NOT started in a function expression, that is, anonymous functions are created in function expressions. The function expressions run as soon as they are defined.

// Function Statement
function a() {
console.log("A Called");
}
a();

// Function Expression
var b = function () {
console.log("B Called");
}
b();

Output -
A Called
B Called

Now what’s the difference ? The answer lies in the concept of Hoisting. When we try to invoke the function before their declaration, Let’s see how they behave :-

a();  
b();

// Function Statement
function a() {
console.log("A Called");
}

// Function Statement
var b = function () { line 2
console.log("B Called");
}

Output -
A Called
Uncaught Type Error : b is not a function // Error incase of invoking b()

When we try to invoke the function before they are declared, a() is works fine but b() throws an error. Reason — In case of Hoisting phase, a() is created a memory and assigned a memory. But b() is treated like a variable it expects the function to be a value so it’s assigned undefined initially and we can’t call the function b() until the code hits the function declaration.

Hope, I am able to explain the difference. Please ignore the grammatical mistakes and try to grab the concepts. I will be trying my best to improve my writing skills.

Thanks for reading and “All the Best” for the future endeaours !!

--

--