Difference between JavaScript function declarations? - javascript

Why does calling my JavaScript function throw an error when I call it like this
wysiwyg2();
var wysiwyg2 = function()
{
alert(1);
}
but work when I do this?
wysiwyg2();
function wysiwyg2 ()
{
alert(1);
}

You need to define your function variable first, i.e.
var wysiwyg2 = function()
{
alert(1);
}
wysiwyg2();
For a good explanation of the difference, see Why can I use a function before it’s defined in Javascript?

In the first snippet, you're trying to invoke a variable before the variable is defined.
You'd get the same problem from the following code:
test.toString();
var test = new Date;
In the second snippet, you're declaring the function without assigning it to a variable, and this results in a global declaration that is usable in earlier code.

You can think of your javascript as though it's evaluated in two passes. The first pass builds all the objects and names (and remember: functions are objects), and places them "in scope", so to speak. It's kind of like a compilation step. Then the second pass executes the code.
So your second sample works because the first pass built and "scoped" the function before execution. The first sample does not work because the function object is created as part of a variable assignment, and so it's not in scope yet when you try to call it.
You mention another situation in the comments, where the function call and definition are separated into two script blocks. That doesn't work because the engine completes both steps of one block before moving on to the next, and you tried to call the function in a block that is executed before the block where it's defined. You can call function across script blocks, but not until they are defined.

In the first one, you're declaring a function and assigning it to a variable. Thus you won't be able to call it through that variable until it's actually assigned to it.
In the second, you're declaring a named function. And can call that function from wherever (as long as it's in scope).

When entering a new execution context (which is either a function call or global code), JavaScript first goes through a variable instantiation phase during which all variable declarations and function declarations within the global code or function body are examined and create as properties of the current variable object, which is effectively a collection of all the objects that are in the current scope. In particular, any function declaration such as
function wysiwyg2 ()
{
alert(1);
}
... is fully created during this phase, while any variable declaration such as
var a = 2;
... only leads to the creation of a variable called a with a value of undefined during this phase. This is also true of a variable declaration with an assignment to a function expression, such as
var wysiwyg2 = function()
{
alert(1);
}
Only the variable instantiation takes place at this point. Once this phase is complete the rest of the code (including variable assignment) is executed sequentially.

Related

IIFE in JavaScript with <<this>> as parameter [duplicate]

In this thread I found a JavaScript code snippet which I want to use.
The code looks like:
(function(global) {
// the function code comes here
})(this);
How can i call this function to execute the code? What do I have to pass in for this global variable?
The function is immediately executed, you do not execute it by calling it.
It is a function literal definition, followed by two parens which causes that function to invoke immediately. Read more: Immediately-Invoked Function Expression (IIFE)
Whatever code you place inside is run right away. Anything placed in the invocation parens is passed into the function as an argument. Assuming your sample code was defined in the global scope, this is the window object, and is referenced as global within the function body. It is a great way to encapsulate your programs to avoid variable collision, force strict mode, and much more.
This construct defines a function:
function(global) {
// the function code comes here
}
and immediately calls it, passing this as a parameter:
([function])(this)
The identifier global is simply the name of this parameter inside the function body. For example, try
console.log(this); // outputs something
(function(global) {
console.log(global); // outputs the same thing as above
})(this);
How can i call this function to execute the code?
It is already being called: (this)
What do I have to pass in for this global variable?
this

Different ways of creating functions in javascript

First of all - yes, I know there are plenty of posts regarding this, or at least very similar ones. Having looked through those I still haven't found the answer to what I'm looking for:
I've learned that there are two main ways to create functions in javascript:
var test = function(a){
console.log(a);
}
Which is created at runtime, and:
function test(a){
console.log(a);
}
Which is created before runtime.
Today I saw this one:
(function test(a){
console.log(a);
})();
I have never seen that before. What separates this one from the two above?
This is immediately-invoke function, it will call itself immediately after declaration.
You can read more about Immediately-invoked function expression at wikipedia.
What separates them is that the first 2 just define the function, whilst the last one defines and executes the function. Typical use for the last one is to reduce global namespace pollution as variables will be scoped to the function not the window.
Your function examples would be considered in Javascript as follows:
Function expression
Function declaration
Immediately invoked function also called a Immediately invoked function expression "IIFE" and self-executing anonymous function.
What happens in what you call 'runtime' is two things. The Javascript engine makes two passes over your code. First pass could be called the declaration pass where variables and function declaration are identified. However, a funny thing happens with variables in this first pass they are said to be 'hoisted' but not initialized. The second pass is the execution pass. Those are the two things that happen in what I think you are referring to as 'runtime'.
The first function what will happen is the same behavior that happens to variables since is assigned to a variable it will be "hoisted" to the top of it functional context and declared but not initialized. So JS will know its a variable but its recognized as undefined until it reaches the section of code that says 'oh' initialize this variable to a function. So you have to wait until after the initialization step to use.
/* This is how function expression looks after
first pass identified but not assigned(initialized) to function
its hoisted and undefined just like a reg variable. */
var test;
//test is undefined here
console.log(test);
//test is initialize here
var test = function (a) {
console.log(a);
}
//test is recognized as a function here
console.log(test);
The second function will be declared(identified) as function in the first pass and you can use it since JS will know right that this function is a function.
//this is recognized as function
console.log(test);
function test (a) {
console.log(a);
}
//test is recognized as function here as well
console.log(test);
The third function will execute itself right away after being declared in the first pass and create it own execution context, self containing.
//test is not recognized here
console.log(test);
(function test(a) {
console.log(a);
//surprise test is recognized here
console.log(test);
})();
//test is not recognized here
console.log(test);
You also have anonymous functions, and named function expressions. Functions are very powerful in JS. Happy Coding!!

how to use (function(global) { ... })(this);

In this thread I found a JavaScript code snippet which I want to use.
The code looks like:
(function(global) {
// the function code comes here
})(this);
How can i call this function to execute the code? What do I have to pass in for this global variable?
The function is immediately executed, you do not execute it by calling it.
It is a function literal definition, followed by two parens which causes that function to invoke immediately. Read more: Immediately-Invoked Function Expression (IIFE)
Whatever code you place inside is run right away. Anything placed in the invocation parens is passed into the function as an argument. Assuming your sample code was defined in the global scope, this is the window object, and is referenced as global within the function body. It is a great way to encapsulate your programs to avoid variable collision, force strict mode, and much more.
This construct defines a function:
function(global) {
// the function code comes here
}
and immediately calls it, passing this as a parameter:
([function])(this)
The identifier global is simply the name of this parameter inside the function body. For example, try
console.log(this); // outputs something
(function(global) {
console.log(global); // outputs the same thing as above
})(this);
How can i call this function to execute the code?
It is already being called: (this)
What do I have to pass in for this global variable?
this

Why is this function wrapped in parentheses, followed by parentheses? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 9 years ago.
I see this all the time in javascript sources but i've never really found out the real reason this construct is used. Why is this needed?
(function() {
//stuff
})();
Why is this written like this? Why not just use stuff by itself and not in a function?
EDIT: i know this is defining an anonymous function and then calling it, but why?
This defines a function closure
This is used to create a function closure with private functionality and variables that aren't globally visible.
Consider the following code:
(function(){
var test = true;
})();
variable test is not visible anywhere else but within the function closure where it's defined.
What is a closure anyway?
Function closures make it possible for various scripts not to interfere with each other even though they define similarly named variables or private functions. Those privates are visible and accessible only within closure itself and not outside of it.
Check this code and read comments along with it:
// public part
var publicVar = 111;
var publicFunc = function(value) { alert(value); };
var publicObject = {
// no functions whatsoever
};
// closure part
(function(pubObj){
// private variables and functions
var closureVar = 222;
var closureFunc = function(value){
// call public func
publicFunc(value);
// alert private variable
alert(closureVar);
};
// add function to public object that accesses private functionality
pubObj.alertValues = closureFunc;
// mind the missing "var" which makes it a public variable
anotherPublic = 333;
})(publicObject);
// alert 111 & alert 222
publicObject.alertValues(publicVar);
// try to access varaibles
alert(publicVar); // alert 111
alert(anotherPublic); // alert 333
alert(typeof(closureVar)); // alert "undefined"
Here's a JSFiddle running code that displays data as indicated by comments in the upper code.
What it actually does?
As you already know this
creates a function:
function() { ... }
and immediately executes it:
(func)();
this function may or may not accept additional parameters.
jQuery plugins are usually defined this way, by defining a function with one parameter that plugin manipulates within:
(function(paramName){ ... })(jQuery);
But the main idea is still the same: define a function closure with private definitions that can't directly be used outside of it.
That construct is known as a self-executing anonymous function, which is actually not a very good name for it, here is what happens (and why the name is not a good one). This:
function abc() {
//stuff
}
Defines a function called abc, if we wanted an anonymous function (which is a very common pattern in javascript), it would be something along the lines of:
function() {
//stuff
}
But, if you have this you either need to associate it with a variable so you can call it (which would make it not-so-anonymous) or you need to execute it straight away. We can try to execute it straight away by doing this:
function() {
//stuff
}();
But this won't work as it will give you a syntax error. The reason you get a syntax error is as follows. When you create a function with a name (such as abc above), that name becomes a reference to a function expression, you can then execute the expression by putting () after the name e.g.: abc(). The act of declaring a function does not create an expression, the function declaration is infact a statement rather than an expression. Essentially, expression are executable and statements are not (as you may have guessed). So in order to execute an anonymous function you need to tell the parser that it is an expression rather than a statement. One way of doing this (not the only way, but it has become convention), is to wrap your anonymous function in a set of () and so you get your construct:
(function() {
//stuff
})();
An anonymous function which is immediately executed (you can see how the name of the construct is a little off since it's not really an anonymous function that executes itself but is rather an anonymous function that is executed straight away).
Ok, so why is all this useful, one reason is the fact that it lets you stop your code from polluting the global namespace. Because functions in javascript have their own scope any variable inside a function is not visible globally, so if we could somehow write all our code inside a function the global scope would be safe, well our self-executing anonymous function allows us to do just that. Let me borrow an example from John Resig's old book:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
All our variables and functions are written within our self-executing anonymous function, our code is executed in the first place because it is inside a self-executing anonymous function. And due to the fact that javascript allows closures, i.e. essentially allows functions to access variables that are defined in an outer function, we can pretty much write whatever code we like inside the self-executing anonymous function and everything will still work as expected.
But wait there is still more :). This construct allows us to solve a problem that sometimes occurs when using closures in javascript. I will once again let John Resig explain, I quote:
Remember that closures allow you to reference variables that exist
within the parent function. However, it does not provide the value of
the variable at the time it is created; it provides the last value of
the variable within the parent function. The most common issue under
which you’ll see this occur is during a for loop. There is one
variable being used as the iterator (e.g., i). Inside of the for loop,
new functions are being created that utilize the closure to reference
the iterator again. The problem is that by the time the new closured
functions are called, they will reference the last value of the
iterator (i.e., the last position in an array), not the value that you
would expect. Listing 2-16 shows an example of using anonymous
functions to induce scope, to create an instance where expected
closure is possible.
// An element with an ID of main
var obj = document.getElementById("main");
// An array of items to bind to
var items = [ "click", "keypress" ];
// Iterate through each of the items
for ( var i = 0; i < items.length; i++ ) {
// Use a self-executed anonymous function to induce scope
(function(){
// Remember the value within this scope
var item = items[i];
// Bind a function to the element
obj[ "on" + item ] = function() {
// item refers to a parent variable that has been successfully
// scoped within the context of this for loop
alert( "Thanks for your " + item );
};
})();
}
Essentially what all of that means is this, people often write naive javascript code like this (this is the naive version of the loop from above):
for ( var i = 0; i < items.length; i++ ) {
var item = items[i];
// Bind a function to the elment
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[i] );
};
}
The functions we create within the loop are closures, but unfortunately they will lock in the last value of i from the enclosing scope (in this case it will probably be 2 which is gonna cause trouble). What we likely want is for each function we create within the loop to lock in the value of i at the time we create it. This is where our self-executing anonymous function comes in, here is a similar but perhaps easier to understand way of rewriting that loop:
for ( var i = 0; i < items.length; i++ ) {
(function(index){
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[index] );
};
})(i);
}
Because we invoke our anonymous function on every iteration, the parameter we pass in is locked in to the value it was at the time it was passed in, so all the functions we create within the loop will work as expected.
There you go, two good reasons to use the self-executing anonymous function construct and why it actually works in the first place.
It's used to define an anonymous function and then call it. I haven't tried but my best guess for why there are parens around the block is because JavaScript needs them to understand the function call.
It's useful if you want to define a one-off function in place and then immediately call it. The difference between using the anonymous function and just writing the code out is scope. All the variables in the anonymous function will go out of scope when the function's over with (unless the vars are told otherwise, of course). This can be used to keep the global or enclosing namespace clean, to use less memory long-term, or to get some "privacy".
It is an "anonymous self executing function" or "immediately-invoked-function-expression". Nice explanation from Ben Alman here.
I use the pattern when creating namespaces
var APP = {};
(function(context){
})(APP);
Such a construct is useful when you want to make a closure - a construct helps create a private "room" for variables inaccessible from outside. See more in this chapter of "JavaScript: the good parts" book:
http://books.google.com/books?id=PXa2bby0oQ0C&pg=PA37&lpg=PA37&dq=crockford+closure+called+immediately&source=bl&ots=HIlku8x4jL&sig=-T-T0jTmf7_p_6twzaCq5_5aj3A&hl=lv&ei=lSa5TaXeDMyRswa874nrAw&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBUQ6AEwAA#v=onepage&q&f=false
In the example shown on top of page 38, you see that the variable "status" is hidden within a closure and cannot be accessed anyway else than calling the get_status() method.
I'm not sure if this question is answered already, so apologies if I'm just repeating stuff.
In JavaScript, only functions introduce new scope. By wrapping your code in an immediate function, all variables you define exist only in this or lower scope, but not in global scope.
So this is a good way to not pollute the global scope.
There should be only a few global variables. Remember that every global is a property of the window object, which already has a lot of properties by default. Introducing a new scope also avoids collisions with default properties of the window object.

JavaScript scope and closure

I'm trying to wrap my head around closures (there's a joke in there somewhere) and I ran across this:
(function () { /* do cool stuff */ })();
How does this work? What's the purpose of putting the function in parens? Why the empty parens afterwards?
The point of this is that any variables declared in the cool stuff will not be created in global namespace. Any function in javascript will create such a scope. Suppose you have some javascript you want to run. If you do this:
var b = 1;
// stuff using b
And some other code uses b, it will get your left over value. (Or, even worse, if some other code sets b before your code runs, then tries to get its old value later, you'd have changed it in the meantime.)
On the other hand, if you have this code, which declares and then calls the a function:
function a() {
var b = 1;
}
a();
And some other code later on uses b, it will not see your values, since b is local to the function. The problem with this, of course, is that you're still making a global name - "a", in this case. So, we want a function with no name - this is why you get the code you described. It declares a function with no name, and then calls it.
Unfortunately, you can't just say:
function() { ... }()
because this will be parsed as a function declaration statement, and then a syntax error. By wrapping the function declaration in parenthesis, you get a function expression, which can then be called. You call it like any other function expression (like a, above), using the second set of parens. For example, if the function took arguments, you'd pass them there:
(function(a) { ... })(1)
That creates a function, calls it, and discards it.
It might be clearer if you look at it like this:
var throwaway = function(){
// do cool stuff
};
throwaway();
This is done to create a private namespace. Code in the function can have functions and variables without worrying about conflicting with other code loaded in the page.
i just came across this post recently. This type of function definition & call is called self-invoking functions.
(function(){ //code })();
The code inside the function will be executed immediately upon its definition.
That construct means declare an anonymous function and run it immediately. The reason you put your code inside a function body is because the variables you define inside it remain local to the function and not as global variables. However, they will still be visible to the closures defined inside this function.
The parens around the function make it clear that the function is an expression. The parens after are the call to the function.
Notice that the function does not have a name.
One closures approach is to pass variables to the function:
(function($, var_1, var_2) {
// use JQuery, var_1 and var_2 as local variables
})($, var_1, var_2);
Putting the function declaration inside parens creates an expression which evaluates to the anonymous function within. Therefore, the first parenthetical evaluates to a function.
The "empty parens" at the end invoke the defined function, so "//do cool stuff" executes immediately.
This is a way to execute code on-the-fly while also keeping variables out of the global scope.
What is illustrated here, however, has nothing to do with closures - at least not directly. Closures are about maintaining a lexical scope after a parent function has already exited.

Categories

Resources