I've seen a lot of apps for the past few weeks that have this kind of script at the beginning of the script:
(function() {
// Code goes here...
});
Can anyone explain this or have a link to some resources about this?
I've seen a lot of apps for the past few weeks that have this kind of script at the beginning of the script:
(function() {
// Code goes here...
});
Can anyone explain this or have a link to some resources about this?
"use strict"
is used to make sure all variables are declared. For instance, I can do without an error:
x = 3;
although it is not declared, but I cannot do:
"use strict";
x = 3;
without throwing an error. I must use:
"use strict";
var x = 3;
"use strict"
can be used for function
s. For example:
x = 3; // no error
myFunc();
function myFunc() {
"use strict";
y = 3; // error
}
You also cannot delete
a variable when in use strict
mode.
Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions.
Anonymous functions are declared using the function operator instead of the function declaration. You can use the function operator to create a new function wherever it’s valid to put an expression. For example you could declare a new function as a parameter to a function call or to assign a property of another object.
Here is the article.
Actually, this would likely be like:
(function() {
"use strict"
var x = 1;
document.write("I am inside the function scope and x=", x, "<br/>");
}())
if (typeof(x) === "undefined") {
document.write("I am outside the function scope and x=undefined");
}
The function creates a scope that you can use to prevent setting variables and such on the global scope. "use strict" helps with keeping code clean and throws errors with common mistakes that can cause bugs (like redeclaring variables of the same name. Notice in the code above, var x is set inside the function scope. Outside the function scope it is undefined. If you loaded these 2 things in different .js files and were from different authors they could each use their own "var x" and they would not conflict because they are in different scopes instead of set on the global scope.
As far as "use strict" mode and what specifically it prevents you can see more details for that in the documentation here: MDN "use strict" docs
For reference, the function at the start of this code is considered an IIFE (Immediately Invoked Function Expression).