Different ways of creating functions in javascript - 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!!

Related

What is the difference between anonymous function and a variable statement with function expression?

For the below 2 functions, I do not understand Function B is not run immediately like Function A when the script is read.
Instead I have to call it startTick(); after the function B.
//Function A
(function () {
console.log("startTick");
clockSection.textContent = getTime();
})();
//Function B
var startTick = function () {
console.log("startTick");
clockSection.textContent = getTime();
};
First you declare a function: (function(){}) and then you call it (function (){})(). Note the parenthesis after the function declaration in your function A. It's callint it. The function B wasn't called, just declared.
The first one is not just an anonymous function, it's an "Immediately invoked function expression" (or IIFE for short).
The function itself is just what's inside the parenthesis and it won't execute by itself, you called it by defining it inside those parenthesis and then calling it through the () at the end of the expression, so in way, you still had to use () just like you did for the second one, it's just that, had you not done that, since it's nameless and not stored in a variable, constant or let, you would've had no way of referring to it later to execute it.
The second one is actually still an anonymous function, you just assigned it to a var instead of enclosing it in parenthesis and calling it right away.
A named function looks like this:
function startTick(){
...
}
Notice it's not assigned to a var or anything, rather, the name was defined after the function keyword. One important difference is that you can call named functions in your code before the line where they are defined (more about that here: var functionName = function() {} vs function functionName() {}. More about functions in general here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions )
Your first function executes immediately (IIFE) because of the final (). The second has to be called: startTick() (Function expression) because you are just assigning a function to a variable and not executing it.
IIFE - Immediately Invoked Function Expressions - are usually used as a way to encapsulate a module or a set of code. It creates a closure that is used as a namespace.
Function expressions are usually used instead of a named function but have no real purpose. It's a matter of style.
function func_name(){...}
This is a function declaration. You define what the function does by this syntax. But it doesn't automatically run right after the declaration.
Whenever you want to run the function you usually invoke the function by
func_name()
after you declared the function somewhere else.
So to answer your question:
Function A:
Inside the very first pair parenthesis is the declaration of your function. Then the second pair of parenthesis is where you actually calling the function.
Function B:
This is just a declaration, which doesn't run itself automatically.
So if you want to run it, invoke it by func_name()
Hopefully, this is clear to you.

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

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

Difference between JavaScript function declarations?

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.

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