Differentiate declaration syntax: function fn() {} vs var fn = function() {} in JavaScript

In the post i discuss why programmers use of function fn() {} and var fn = function() {} in JavaScript?  What is difference between these two functions and pros & cons of using the functions. The problem you face when you reuse or optimize the code of another developer, you get confuse why he used function fn() {} in one place and var fn = function() {} in another line of code, after reading the post you get better idea of these two functions.

 var fn = function() {} is a function expression while function fn() {} is a function declaration  and it is define when script is executed.

Example of function expression.

// TypeError: undefined is not a function

  var functionexp = function() {

Example of function declaration.

 // Outputs: “Hello!”

  function functiondec() {

Another difference of function expression and function declaration, are you can not add function declaration in conditional statements (if, if else, switch etc) of JavaScript. if you want to use function in conditional statement use “use strict” in the function or start of the JavaScript file. More about strict mode.

About Moazzam Qureshi

I am SEO expert and web developer since 2011. My hobby is to write & provides quality content about blogging, SEO , Social Media , Earn Online and Affiliate Marketing.

Leave a Reply