Reputation: 2387
So if have:
var num = (function(){
return 1 + 1;
})();
Will that function be processed every time I use that variable? Or is it only processed the first time the browser reads over the script and the return result 'permanently' assigned to that variable?
Upvotes: 1
Views: 27
Reputation: 1010
Let's make a test, consider the following script :
var timestamp = (function(){
return Date.now();
})();
console.log('variable at time t : ' + timestamp);
setTimeout(function() {
console.log('variable at time t+1s : ' + timestamp);
}, 1000);
This returns the same timestamp, we can conclude that the timestamp variable is assigned the value of the self-calling function only once.
Upvotes: 1
Reputation: 3739
(function(){ return 1 + 1; })();
is a self-executing anonymous function
. Which means it will be executed as it is defined once and its value returned. If you want the function to be assigned to a variable simply use
var func = function(){ }
Upvotes: 0
Reputation: 413846
JavaScript is not a lazy language. ("Imperative" is one way to describe the language; I'm not the one to give the most accurate term.) The expression on the right-hand side of the =
assignment operator will be evaluated once, and the result will be stored in the variable.
Upvotes: 2