This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 8 years ago.
I was reading about AngularJS and came across the following statement on a newsgroup:
I have to say, though, that the more I use Angular, the less interest
I have in creating classes. Classes are not where javascript is at!
You can do pretty much everything you need with pure functions and
closures and then you don't have to worry about the troublesome
"this" and "that".
Can someone explain what is meant by "closures".
Closures are a structure in Javascript code where within nested functions the outer functions scope is retained within the inner function.
For Example:
function outer(x,y){
var t = 1;
return function(z){
//x, y, t from the outer function are made available to inner function
return x + y + z + t;
}
}
var outer1 = outer(1,1); //creating a closure, or an instance of a function in sense
alert(outer1(1)); //Alerts 4
var outer2 = outer(2,2);
alert(outer2(2)); //Alerts 7
The simple explanation of a Closure is that ECMAScript allows inner
functions; function definitions and function expressions that are
inside the function bodes of other functions. And that those inner
functions are allowed access to all of the local variables, parameters
and declared inner functions within their outer function(s). A closure
is formed when one of those inner functions is made accessible outside
of the function in which it was contained, so that it may be executed
after the outer function has returned. At which point it still has
access to the local variables, parameters and inner function
declarations of its outer function. Those local variables, parameter
and function declarations (initially) have the values that they had
when the outer function returned and may be interacted with by the
inner function.
Source
Related
This question already has answers here:
Function and variable with the same name
(2 answers)
Closed 5 years ago.
Might be a kind of easy question, but I have a question on the issue of having the same name for a variable and a function.
If there's a variable,
var add = 1;
and a function,
function add(x,y) {return x+y;}
and there're two console.log,
console.log(add)
console.log(add(1,2))
I've expected those 2 console.log would work properly since add contains the Number and add() is classified as a Function, but the second one prints an error. So they aren't considered the same.
But the result says I'm wrong.
Can anyone explain what's going on in my code?
Variables and function definitions(not expressions) are hoisted to up, it means that wherever in scope you wrote your function or variable they will be moved to the start of the scope. First goes functions definitions then variables. So it means that functions will be overwritten by variables.
var add = 1;
function add(x,y) {return x+y;}
console.log(add);
The order doesn't matter. Later will be the variable and will overwrite
function add(x,y) {return x+y;}
var add = 1;
console.log(add);
This question already has answers here:
What are the advantages/disadvantages for creating a top level function in ES6 with arrows or without?
(2 answers)
Closed 6 years ago.
I have downloaded an open source js code where the developer often create new function in this way:
var log = msg => div.innerHTML += "<br>" + msg;
So, is there a difference with this below ?
function log(msg){
div.innerHTML += "<br>" + msg;
}
There are some differences between arrow functions and function foo() {} functions. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions.
A few I can think of off the top of my head:
function foo() {} function definitions are hoisted, which means you can invoke such a function anywhere in the scope that contains its definition. This is not the case for variables containing functions, for which only the declarations are hoisted
Arrow functions bind this lexically, which in simple words means that they do not introduce their own this variable. Instead, they simply close over the nearest this variable from an enclosing scope
Arrow functions do not have the arguments local variable available for use within the body
All that said, the two functions you have shown should behave identically in most cases, given the caveats mentioned above.
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 7 years ago.
In javascript, what's the purpose of assigning variable to function declaration?
var test = function(){console.log("Hello world")}
over
function test(){ console.log("Hello world")
Also, I don't understand the code below does not work. Is it because hoisting does not care about variable assignment? (cares only about variable declaration)
vartest();
var vartest = function(){
console.log("Hello var function")
}
The first part is not answerable. There's no "single purpose" and there are varied use cases for this.
The second part is simpler. Hoisting can be described as "pulling up declarations". This means that variables and functions are effectively always declared at the top of their scope. That does not mean they are assigned values at the top. Values are assigned at the original location of the "pre-hoisting" declaration. However, since named functions are not assigned a value, the hoisting effectively moves the declaration and implementation as a whole to the top of the scope.
This does not happen for functions assigned to variables, and hence the code "does not work".
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 7 years ago.
function animator(shapes, $timeout) {
(function tick() {
var i;
var now = new Date().getTime();
var maxX = 600;
var maxY = 600;
var now = new Date().getTime();
$timeout(tick, 30);
})(); // What is this for?
}
Here I don't understand the functionality. I am new to this kind of script. Inside of the main function is like ()(). What is this for?
This is an IIFE, Immediately-invoked function expression.
Why use an IIFE?
Why?: An IIFE removes variables from the global scope. This helps
prevent variables and function declarations from living longer than
expected in the global scope, which also helps avoid variable
collisions.
Why?: When your code is minified and bundled into a single file for
deployment to a production server, you could have collisions of
variables and many global variables. An IIFE protects you against both
of these by providing variable scope for each file.
I don't know if it has a separate name, it's just immediately executed.
Instead of function a(){..}; a() you can do (function(){..})()
Useful for scoping the vars inside, while placing/executing it right where you want it, also you don't have to invent a name for it.
(function(){console.log('test')})() will call function immediately. So if you will write this statement then it will be called immediately and prints test on console.
This is a self-invoking function as #lix pointed out.
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.