Function Statements Vs Function Expression

Function Statements Vs Function Expression

Often JavaScript developers are found encountering the above question in their interviews. Both are ways to create functions and looks the same but there is a slight difference in them. Let's understand the difference and answer them appropriately to create a profound image before the interviewer.

Function Statement - When we declare a function with function keyword and a name with a body, it's called function statement.

Function Expression - When we assign a function to a variable, then it's called Function Expression. Below is an example to have a clear picture of them.

// 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 TypeError : 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 endeavours.


要查看或添加评论,请登录

Rakesh Kumar Shaw的更多文章

  • JavaScript Shorthand trick

    JavaScript Shorthand trick

    Today, I will discuss some shorthand techniques for regularly used syntax to ace an interview and save our time while…

    4 条评论
  • Some Common JavaScript mistakes

    Some Common JavaScript mistakes

    JavaScript is among the most popular languages for web development today. It’s fairly easy to start, and boasts of some…

  • Short Hand coding Tricks in JavaScript

    Short Hand coding Tricks in JavaScript

    Often, developers are found writing trivial codes that could have been done in a concise way, making it more readable…

    2 条评论
  • Higher Order Function JavaScript

    Higher Order Function JavaScript

    If you are learning JavaScript, you must have come across the term Higher-Order Functions. Although it may sound…

    3 条评论

社区洞察

其他会员也浏览了