Arguments of self executing function [duplicate] - javascript

This question already has answers here:
How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?
(5 answers)
Closed 9 years ago.
(function (global, undefined) {
... some code which doesnt use arguments array
} (this));
I often see module pattern done in this way.
I really question why there's a second argument undefined?
Are these examples buggy or is there a special meaning of undefined here?

undefined is a global property that is widely used. In older versions of JavaScript it is possible to change the value of it (for example, to true). This generally breaks everything.
By changing its scope to be local to the "module" (i.e. the function), other modules are prevented from interfering with it.
This allows code to safely use undefined instead of having to use global.undefined.
MDN Reference

Related

JavaScript - Unset argument [duplicate]

This question already has answers here:
Are variables statically or dynamically "scoped" in javascript?
(7 answers)
What is the scope of variables in JavaScript?
(27 answers)
What is lexical scope?
(21 answers)
Lexical Scope in JavaScript
(4 answers)
Closed 8 days ago.
I am working on a large library and I want to reduce conflicts in the code as much as possible. I have a function like this:
((privateArgument) => {
var transformed = privateArgument.someProperty;
userCallback(); // This should only have access to transformed
})({someProperty: 'Hello, world!'});
I should mention that I tried to simplify the example as much as possible to illustrate my intention. In reality, I have no control over the value passed to the function ({someProperty: 'Hello, world!'}).
And an example of the userCallback:
() => {
console.log(transformed); // Can be used here freely
console.log(privateArgument); // Can unfortunately also be accessed
}
I have tried the following:
Setting privateArgument = undefined: breaks access to transformed and does not throw the native "undefined" error
Overriding the privateArgument by defining a new let privateArgument and scoping the userCallback with {}: gives me an error, saying that I cannot redefine it
Passing transformed as an argument to userCallback: does nothing to address the issue
Please note that I am specifically asking about arguments, not regular variables such as var and let. I am aware that the issue regarding normal variables has already been addressed in other questions. However, the answers to those questions are not helpful for this particular issue.
If anyone knows of a scoping mechanism I can utilize for this or how to completely get rid of the privateArgument (so that it throws the native error and can be re-declared in the userCallback) it would be greatly appreciated.

JavaScript function evaluating itself and calling itself at the same time [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 7 years ago.
I am learning about JavaScript functions on MDN
I came across an example that looks similar to this:
var saySomething = ( function(){console.log("hello")} )();
I have also seen this in the jQuery source.
I have not found any explanation of this style of function calling/definition on the MDN function reference.
I know from running the code that it calls itself immediately upon interpretation by the JavaScript engine.
Is this the Grouping Operator in action? Where it says:
First evaluate the body of this function and return it
Since the parentheses () immediately follow it it gets called ?
Google "Immediately Invoked Function Expression" or "IIFE".
The general syntax looks like this:
(function(){
// do something here
})():
Sometimes you'll see arguments passed in as well. It's basically used to wrap your code so none of your variables leak out into the global namespace.

What does function($) mean? [duplicate]

This question already has answers here:
What does function($) mean in javascript?
(3 answers)
Closed 9 years ago.
I just started learning JavaScript. Found a statement function($) { ...} while checking out examples. Can anyone tell me what function($) means?
It means "This defines a function. When it is called: create a local variable called $ and assign the value of the first argument to it."
First off: This creates a function where $ is the first argument passed to it. It could look like this potentially:
function dollar($){
alert($);
}
dollar("hello")
//alerts "hello"
Typically this is used when you want the $ to mean jQuery.
For example:
(function($){
//stuff where $ === jQuery
})(jQuery)
Means that jQuery will be passed into the $ variable for the scope of anything that happens in that function.
This can be useful if you have multiple libraries within the global scope that may use the $ variable, but you have a modular plugin that refers to the necessary library as that and you don't want to rewrite the whole thing.
Note: It does not always mean jQuery but in about 80% of cases it will. Otherwise it is just a convenient way to bind a library to a shorter variable within a certain scope.

What is this syntax? ; (function ($, undefined) [duplicate]

This question already has answers here:
What does (function($) {})(jQuery); mean?
(6 answers)
Closed 9 years ago.
; (function ($, undefined)
{
// all the variables and functions of the js document
})(jQuery);
I've seen this twice now in the jquery/javascript files for a zoom script. I don't understand what this is exactly. I can't seem to google it, I don't remember coming across this on tizag or w3schools while recently learning jquery and js.
There's nothing before or after this code (other than some comments). So I'm utterly lost as to what (function())(jQuery); is or does.
(function ($, undefined)
{
// all the variables and functions of the js document
})(jQuery);
calls a block of code ensuring that inside
$ is usable to refer to jQuery
undefined is undefined (edit: this was useful because undefined could be redefined at that time in the oldest browsers, it's now useless)
and that any minifier can change undefined to a shorter label.
The initial ; ensures you can concatenate this file with another one : without this, you'd have an error executing the concatened file if the one just before was something like
(function (){
})()
This is a way to ensure that $ is indeed the jQuery object and to ensure that any local variables and methods are privately scoped, that is, do not pollute the global namespace.
It is a self-calling anonymous function, with the parameter passed being jQuery, meaning that the $ will be the jQuery object.
Being declared inside a function means that the inner variables and methods will not be visible outside of it.

Can you set an undefined variable as a function parameter? [duplicate]

This question already has answers here:
Undefined variable as function argument javascript
(2 answers)
Closed 8 years ago.
I am building a function to match types of variables. It will be an alternative to typeof <var> === "something".
My function call looks like this : is("some text")["string"]. It returns true, or is([])["element"]. Now it returns false, But I have an issue with it.
For example, if I try to send an undefined variable like "undefVar" to a function I am expecting something like this: is(undefVar)["undefined"], but I get an error which says that "undefVar" is not defined.
Can I somehow make my function work using undefined variables? Is this possible at all?
p.s: I have to use this function a lot so it seems (for me) that it would be better to use something like this : is(var)[type] as opposed to typeof var === type.
typeof is special on nonexistent variables. You cannot mimic it with a function.
No, you cannot blindly pass undefined variables to your function from the call site and globally change the behavior of the JS engine to accomodate this.
typeof is a built-in operator and is not bound by the rules of "common" functions, which is why it can do things that custom functions cannot.
Finally, I strongly disagree that it would be practically preferable to use an alternative syntax even if that were possible.

Categories