javascript - (function(){}) vs function(){}(); -
this question has answer here:
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
xin 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
Comments
Post a Comment