javascript - (function(){}) vs function(){}(); -


consider following 2 examples:

first:

var x = (function(){  return 786;  }()); 

second:

var y = function(){  return 786;  }(); 

i know can't use function(){ return 786; }(); directly anoomymus self calling function since assigining variable x can use function. so,

  • is there difference in result of behaviour of variable x in first , second method?

no. there wouldn't difference.

wrapping function in parentheses converts them function declaration expression , ok valid expression run on own.

var x = (function(){  return 786;  }()); 

here, anonymous function wrapped in parentheses expression executes function , return 786, assigning var x. since anonymous function valid expression, can run separately also.

var y = function(){  return 786;  }(); 

here, complete statement assignment expression , thus, executed , stores value 786 var y.

for further reading, check out following links:

/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions

http://kangax.github.io/nfe/#function-statements


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -