What’s the difference between these?
var person = {
age: 25,
name: "David"
};
var person = (function() {
var name = "David", age = 25;
}());
My question really is, what does (function(){}()) do?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What does
(function(){}())do?This essentially creates an anonymous function and then executes it. One common use for this is limiting global variables.
For example, the following would have three global variables (
var1,var2, andvar3):If you wrapped these declarations in the anonymous function, they’re still accessible as local variables within the anonymous function, yet do not cloud up the global namespace. For example:
What’s the difference between these?
If this code is contained in a function, it creates a local variable named
person. Otherwise, it creates a global variable namedperson.This code creates and executes an anonymous function, then assigns the return code of that anonymous function to the variable
person. Since the anonymous function has no return value, the variablepersonhas a value ofundefined. This statement, as it currently stands, is functionally equivalent tovar person;, because the anonymous function has no side-effects and doesn’t have a return value.