Don't understand how Closure Functions are working? [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 6 years ago.
I am reading eloquentjavascript to learn javascript but this closure thing is confusing me. warp1 is not function but it looks like function and it looks like taking argument too. How do closure functions work ? and what are the reasons we can use it ?
function wrapValue(n) {
var localVariable = n;
return function() { return localVariable; };
}
var wrap1 = wrapValue(1);
var wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2

The outer function (wrapValue) returns a function. So the returned function gets assigned to your variables wrap1 and wrap2. That's why you can call the returned function from your variable.
Maybe it's easier to understand when we look at the following.
You can create a function like you did:
function foo() { return "foo"; }
Or you can assign a function to a variable:
var foo = function() { return "foo"; }
The second example basically does exactly the same as your closure does - it assigns a function to a variable.
In all cases, you can call the function with
foo();
Either by variable, or function name.

Related

What exactly is function expression? [duplicate]

This question already has answers here:
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Why JavaScript function declaration (and expression)?
(5 answers)
Why use named function expressions?
(5 answers)
Closed 1 year ago.
I thought before that function expression can be any function that is store in some variable. For example, this is function expression, because function is stored in func variable.
let func = function() {
console.log(5);
};
And here's function expression, because callback function is stored in function's paremeter callback.
function func(callback) {
callback();
};
func(function() {
console.log(5);
});
//That's what I mean:
//let callback = function() {...}
But... recently I've found out that this callback function can also be considered as function expression. Why? This function isn't stored in some variable.
let arr = [18, 50];
let obj = {
name: 'Karina',
};
arr.forEach(function func(value) {
console.log(`${this.name} is ${value} years old`);
}, obj);
So, my question is...What exactly make function function expression?
I thought before that function expression can be any function that is store in some variable.
No. The variable to store to does not matter. The let func = …; is not part of the function expression, the function expression is only the part (expression) that comes in the middle.
let func = function() {
// ^^^^^^^^^^^^
console.log(5);
//^^^^^^^^^^^^^^^^^^
};
//^
This function isn't stored in some variable.
Actually there's no difference between your second and third snippet. You're passing the function constructed from the expression to a function, regardless how that function is declared (with parameters, with rest syntax, without parameters, or as a builtin like forEach).
But yes, you can have function expressions completely without variables, like in
!function() {…}();
// ^^^^^^^^^^^^^^
void function() {…};
// ^^^^^^^^^^^^^^
(function() {…})();
// ^^^^^^^^^^^^^^
Basically, function expressions are just the literal syntax (as in: object literal, string literal) for function objects.
I'm also learning about functional programming and found out that using a function as a value is indeed a function expression, as you said, by assigning an anonymous function to a variable. But I think the main difference relies on the function declaration being hoisted right? So context comes to play and all of that fun stuff :)

javascript function declarations and differences in scope [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
I couldnT find an answer easily, so even if this question is a dupe, the answers donT come up using these keywords.
I want to know the difference between the different way of declaring functions in a sample app.js
var foo = function()
{
//..
}
function bar()
{
//..
}
var baz= function()
{
//..
}
function qux()
{
//..
}
// other??
I m also not clear about the scope where I can use each function. Thanks!
There are four ways to create a function in JavaScript.
Function declaration
This will create a variable foo in the current scope and assign a named function to it.
function foo () {
}
Function declarations are hoisted so it doesn't matter where, in the applicable scope, you put them. It is considered good coding practise to define them before you use them though.
Anonymous function expression
This will create a function without a name and use it in an expression. In this example it is assigned to the variable something.
something = function () {
};
Named function expression
This is the same as an anonymous function expression except that it has a name, creates a variable of that name in the scope of itself and is horribly broken in older versions of Internet Explorer.
something = function foo () {
};
Function constructor
Do not use function constructors. They are eval by another name. You can read about them on MDN if you're interested.

Access closure variable [duplicate]

This question already has answers here:
How to access javascript variable stored in function closure from browser console?
(2 answers)
Closed 9 years ago.
I have a feeling I know the answer to this question, however is there anyway to view the current value of inside via console?
var test = (function() {
var inside = 0;
return function() {
inside++;
console.log(inside);
return inside;
}
})();
Just call test() and console.log will print the value.
Your closure is self invoked but your inner method is just returned so it is never called in your example.
You should use:
var test = (function() {
var inside = 0;
return function() {
inside++;
console.log(inside);
return inside;
}
})();
test();//Will print 1
So it will create the closure and your return statement will put the inner function in the variable test. So your test became the inner function. Then you need to call it.

Beginner Javascript: What's the difference between 'function xyz(){}' and 'var xyz = function(){}'? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
I've been going through CodeAcademy's Javascript courses, and a few things have gone over my head. I understand how function work, and I'm trying to wrap my head around OOP and objects/methods.
My question is, what's the difference between creating a function like this:
function countTo(number){
for (var i=1; i<=number; i++){
console.log(i);
}
}
countTo(15);
and creating a function like this:
var countToTwo = function(number){
for (var i=1; i<=number; i++){
console.log(i);
}
};
countToTwo(27);
Both do the same thing and have the same output. Are they exactly the same/interchangeable? Does it matter which one I use when creating a function?
The first one is a function declaration, and is "hoisted", meaning it's immediately available anywhere in the context.
The second one is a function expression, and is treated just like any other variable declaration/assignment. The declaration of countToTwo is hoisted and immediately available anywhere in the scope in which it's declared, but the assignment stays in exactly the same place.
The short of it is that you're not able to call a function declared as an expression until the expression has been parsed.
This code should illustrate a little more clearly.
foo();
//blah();
function foo(){
alert('hoisted and works');
}
var blah = function(){
// not hoisted, would fail if called
}
​
Live Demo

Why are anonymous functions treated differently from named functions here? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
Today I stumbled upon the following phenomenon:
foo();
bar();
function foo()
{
console.log("inside foo");
}
var bar = function()
{
console.log("inside bar");
}
FireBug complains with the following error message:
bar is not a function
Several tutorials claim that function f() and var f = function() are basically the same thing. Evidently, they are not, but what exactly is going on here?
Function declarations are available anywhere in the scope they're defined in, even before their physical definitions.
var bar = function() { ... }; is a normal variable that happens to hold a function. Like all other variables, it can only be used after its assigned.
(You cannot observe the future value of a variable)

Categories

Resources