See this example:
var tools1 = require('../tools/tools1');
var test_func = function(arg1, arg2, arg3) {
var local_var_1 = "lc1";
var local_var_2 = "lc2";
return function(data) {
var result = tools1.doSth(local_var_1);
result = result+local_var_2;
}
}
exports.test_func = test_func;
I do not understand what does inner function do what it is for!
In javascript when you return function it returns reference of that function and you can call it later.
In your Code when you do var result = test_func(), result will hold reference of that function. Then later you can call that returned function like result(data).
A basic example:
function sum(x, y) {
var rs = x+y;
return function(message) {
console.log(message + rs); //rs holds its value because of clousers
}
}
var result = sum(2, 3);
result("This is result: ");
Variables that are used locally, but defined in an enclosing scope
like rs in above example because of Closures
This concept of function inside a function is known as closure in JavaScript. They are self invoking and makes it possible to have a function's private variables.
I am representing a similiar code of yours which I found in W3schools.com.
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
Initially, the counter is set to 0 and then it returns a function reference. The counter is protected by the scope of the anonymous function, and can only be changed using the add() function.
The counter is set to 3 then, as add() function is called three times.
In the very similiar way, your code is working I guess:
var test_func = function(arg1, arg2, arg3) {
var local_var_1 = "lc1";
var local_var_2 = "lc2";
return function(data) {
var result = tools1.doSth(local_var_1);
result = result+local_var_2;
}
}
the local_var_1 and local_var_2 is set to "lc1' and "lc2" and returning a function reference.
The inner function then comes and do some operation with tools1.doSth() on local_var_1 and append the result with local_var_2.
Note: I am not clear with the output of your code, so I tried to tell you the steps with help of another code.
Related
I am confused about scope when comparing normal function and immediate function.
Here is a example:
var num=5;
var x=3;
doubleNum = function(){
num = num*x
x++;
return num;
};
console.log(doubleNum());//15
console.log(doubleNum());//60
console.log(doubleNum());//300
This is a normal function that num and x are defined globally and accessible by doubleNum, as a result num and x are updated.
var num=5;
var x=3;
doubleNum = function(){
num = num*x
x++;
return num;
}();
console.log(doubleNum);//15
console.log(doubleNum);//15
console.log(doubleNum);//15
However if I define a immediate function and call it same way as above, I got different answer. Even I am expecting to have same output
Did I miss something essential? Or did I understand some concept wrong?
Please help.
Thanks in advance.
Jsfiddle
Because your doubleNum is not a reference to the function, but keeps the result of an anonymous function call.
In the first case you assign to the doubleNum a function and every time calling it via doubleNum(), you change the outscoped variables inside it and return a num. You do this 3 times. Your code is equivalent something to like
var num=5;
var x=3;
doubleNum = function(){
num = num*x; // Every call will affect the outscoped num
x++; // Every call will affect the outscoped x
return num;
};
var val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
In the second case you assign to the doubleNum the result of a single call anonymous function. The function value is already computed one time and assigns the result to the doubleNum. Your code is equivalent something to
var num=5;
var x=3;
var doubleNum;
var myFunction = function(){
num = num*x;
x++;
return num;
};
doubleNum = myFunction(); // Only one call
console.log(doubleNum);
console.log(doubleNum);
console.log(doubleNum);
Did I miss something essential?
Just that in the second case, the value of doubleNum is already computed because the function is invoked as soon as it is defined.
On the other hand, in the first case only function definition was assigned to doubleNum rather than the result of its invocation.
The immediate function call is being evaluated only once. You're allocating a value not an immediate function to doubleNum. To accomplish a similar effect, try using a class and getters.
class ClassName {
constructor(){
this.num = 5;
this.x = 3;
}
get doubleNum() {
this.num = this.num*this.x++;
return this.num;
}
}
var double = new ClassName();
console.log(double.doubleNum);//15
console.log(double.doubleNum);//30
console.log(double.doubleNum);//300
I'm new to functional programming and I'm trying to learn it in javascript. I found some examples and wrote my own snippet, but I don't understand WHY it works. There is a function called whatTheHeckIsThis. Can someone tell me what it is doing or what its purpose is? Note that when running this code, the output is true.
function boolFlipper(someFn){
return function whatTheHeckIsThis(x,y){
return !someFn(x,y);
};
}
var checkStrings = function(x, y){
return x === y;
}
var flipperTester = boolFlipper(checkStrings);
var str1 = "this string";
var str2 = "that string";
console.log(flipperTester(str1, str2));
My confusion is why can't I just do this instead:
function boolFlipper(someFn){
return !someFn(x,y);
}
a reference to whatTheHeckIsthis() will be returned and stored into flipperTester
After this, flipperTester can be used like a function.
You can use this language feature to abstract some code.
Simple example:
function addTen(x) { return x + 10 }
function multiplyByTen(x) { return x * 10 }
...
var doMath
// somewhere a user selected something
if (userInputSaysAdd) doMath = addTen
if (userInputSaysMultiply) doMath = multiplyByTen
// this will be the choosen function
doMath(someValue)
Your second version doesn't work for 2 reasons:
The purpose of boolFlipper is to return a new function, which you can assign to another variable and later call.
Your function doesn't have x and y parameters.
To solve #2 you could write:
function boolFlipper(someFn, x, y) {
return !someFn(x, y);
}
You would then have to call it like:
console.log(boolFlipper(checkStrings, str1, str2));
But you still couldn't do:
flipperTester = boolFlipper(checkStrings);
The original snippet returns a closure, which is bound in the environment where someFn is equal to the function passed as an argument to bookFlipper(). You can then assign this function to a variable, and call it with new arguments, that are assigned to x and y, and then the the function saved in someFn() is called, the return value is negated with !, and this is returned.
For more information about closures, see How do JavaScript closures work?
In JavaScript functions are objects, so you can return them. When you return a function you are getting a function object, so you can call it as any other function. For example:
function myFun() {
return function() {
console.log("test");
};
}
var functionInside = myFun();
/* This is like doing:
var functionInside = function() {
console.log("test");
};
*/
functionInside(); // This will execute the function.
Example with your code:
This variable:
var flipperTester = boolFlipper(checkStrings);
contains a function like this:
var flipperTester = function (x,y) {
return !someFn(x,y);
}
And this is something similar to
function flipperTester(x,y) {
return !someFn(x,y);
}
So when you do:
flipperTester(str1, str2)
You are executing that function. The variable "someFn" inside there is the function "checkStrings", because you passed it when you initialize flipperTester variable.
boolFlipper is, for our purposes here, a function decorator: it takes a function and modifies it to do something else. A more instructive example might be a logging function:
var alsoLogs = f => (...args) => {
var result = f(...args);
console.log(result);
return result;
};
// now we have a function that adds 2 numbers:
var add = function add(a, b) { return a + b; };
// and we want to also log the result
var addAndLog = alsoLogs(add); // addAndLog is a function, would be the whatTheHeckIsThis from your example
addAndLog(2, 3); // logs 5 to the console
If you don't understand all the ES6 syntax that's ok, just understand that alsoLogs take a function f and returns a function that does the exact same thing as f but also logs the result to the console.
Since we as programmers are lazy, we don't want to have to write functions to glue together other functions every time we want to do this, so we write a function to do it for us, compose.
So now we can just say something like:
var addAndLog = R.compose(console.log, add);
addAndLog(2, 3); // logs 5 to the console
I am new to Javascript and learning about closures and nested scope.
The prompt asks for this:
Write a function that has three nested functions, each taking one number as an argument. The inner-most function should return the sum of all three numbers.
This is what I have come up:
var outMost = function (num1) {
var x = num1;
var innerMost = function (num2) {
var y = num2;
var innerInnerMost = function (num3) {
console.log(x + y + num3);
}
return innerInnerMost;
}
return innerMost;
}
var firstNum = outMost(1);
firstNum(2);
firstNum((3));
Please help me understand what I am doing wrong -- I have gone on numerous website to learn about closures and scope but nothing seems to explain it well. Thank you for the help.
When you call firstNum(2), you are not catching the return-value (which is a function). If I run your code in Node.js REPL, here is what it looks like:
> var firstNum = outMost(1);
undefined
> firstNum(2);
[Function]
> firstNum((3));
[Function]
Try this in the end instead:
var firstNum = outMost(1);
var secondNum = firstNum(2);
secondNum(3);
Here is what it looks like in Node.js REPL:
> var firstNum = outMost(1);
undefined
> var secondNum = firstNum(2);
undefined
> secondNum(3);
6
undefined
Please note that assignment evaluates to undefined. Also, since innerInnerMost doesn't return anything, there is an implicit return undefined in the end.
function firstFunc(x){
return function secondFunc(y){
return function thirdFunc(z){
console.log(x+y+z);
}
}
}
Calling:
var ff = firstFunc(1);
var sf = ff(2);
sf(3);
very easy look at this example
if you have this type
in ES6
let f = () => {
return () => {
console.log('First function called');
return () => {
console.log('Second function called');
}
}
}
you have two way to call every function, first of all, I want to call the First function
in this way f()() and then I want to call the Second function f()()().
First of all, you will be seeing in console
First function called
and then
Second function called
and another way you can use this technic
let f1 = f();
let f2 = f1();
you will be seeing
First function called
if you want to the second function call
let f1 = f();
let f2 = f1();
let f3 = f2();
and then you will be seeing
Second function called
if you want to change this code to ES5
var f = function() {
return function() {
console.log('First function');
return function(){
console.log('Second function');
}
}
}
two way of call
var f1 = f();
var f2 = f1();
var f3 = f2();
f()()();
I try to figure out, how closure works, this is my example
function func1(func) {
return function(summand) {
return func() + summand;
}
}
var func2 = function() {
return 3;
}
var func3 = func1(func2);
var value = func3(4);
alert(value);
var func2 = function() {
return 100;
}
var newValue = func3(100);
alert(newValue);
First of all let breaks down the code. I write a function that expected as parameter a function and it will return a function.
function func1(func) {
return function(summand) {
return func() + summand;
}
}
Then i defined the parameter function func2 in expression form
var func2 = function() {
return 3;
}
then call func1 and give func2 as pamerater. As result i have got a function back
var func3 = func1(func2);
then i execute function and pass 4 as parameter argument
var value = func3(4);
as result i've got 7. Then i overwrite func2 and return 100
var func2 = function() {
return 100;
}
then call func3 again and pass as parameter value 100.
var newValue = func3(100);
as result i've got 103. The first function that i defined(that return a function and takes function as parameter), will still used the first version of func2. This the power of closure, i know it.
But look at the following code, when i define func2 as function declaration not as expression, then func2 will overwrite
function func1(func) {
return function(summand) {
return func() + summand;
}
}
function func2() {
return 3;
}
var func3 = func1(func2);
var value = func3(4);
alert(value);
function func2() {
return 100;
}
var newValue = func3(100);
alert(newValue);
The first value is 104 and second is 200.
My question is, why when i use function declaration it will overwrite the old function, in this example is func2. But when i use function expression it will keep the reference to old func2.
It that because of function hoisting?
This is not because of closures.
Just like you figured out - this issue is because of function hoisting.
You can think of function declarations as "moved up" to the start of the current scope.
var f2 = function(){
return 50;
}
function f2(){
return 100;
}
In this case, f2 is 50 because it gets parsed in a way that's similar to:
var f2 = function(){
return 100;
}
var f2 = function(){
return 50;
}
Because of hoisting.
It is because of hoisting. Using the function statement rather than the function expression causes the function func2 to get hoisted to the top of the scope. You are overwriting func2 before any code in the scope gets executed.
because of hoisting you code actually looks like this:
function func1(func) {
return function(summand) {
return func() + summand;
}
}
function func2() {
return 3;
}
// Hoisted!!! Overwriting the previous func2 definition.
function func2() {
return 100;
}
var func3 = func1(func2);
var value = func3(4);
alert(value);
var newValue = func3(100);
alert(newValue);
Inside func1, func is a stable reference to the function that it was passed... It's just that you are passing the return 100; version before you think you are.
When you use the function foo() { ... } style, you are defining a function with the name foo. When you use the var foo = function() { ... } style, you are declaring a variable foo (which will be hoisted), and assigning it the anonymous function as its value.
It is ok to write
var a;
a = 2;
// ...stuff...
a = 3;
and we expect the value to be 3. So it is here, hoisting makes this like:
var func2;
func2 = function() { .. some stuff.. };
// ...stuff...
func2 = function() { .. some other stuff .. };
By comparison, I think if you define the functions, it will just take the one or other function definition in the initial parse.
i'm creating a game in javascript for college and i have a button to call a function but i need it to include variables from another function
if i put the function inside the other function where the variables are the button doesn't call it
is there a way of doing this or to get the variables that were created in the first function and use them in the second function
it is a simple maths game where you get a random number a random sum and another random number
(i.e. 5+7, 4*3, 2/6, etc,)
so i've got a function to show the random number using
var ranNum1a=Math.floor(Math.random()*10);
i need the other function to check the users answer but i need to know what the random number was from the other function
You would need to make those variables global
example:
var myValue;
function setValue()
{
myValue = "test";
}
function getValue()
{
alert(window.myValue); // yup, it's "test"
}
source..
For simplest case, passing variables to another function might be the best approach to this problem.
Here is an illustration:
function f1(var1, var2) {
//do you stuff then pass the variable to another function
f2(var1, var2);
}
function f2(v1, v2) {
// here v1 will get the value from var1 and v2 from var2 if passed from within the function f1
}
var ranNum1a;
function show() {
ranNum1a = Math.floor(Math.random()*10);
// show it
}
function check() {
if (ranNum1a == 42) {
alert("Ok");
}
}
I found this to be extremely helpful in relation to the original question:
Return the value you wish to use in functionOne, then call functionOne within functionTwo and place the result into a fresh var. This should enable you to use the var declared in functionOne, within functionTwo.
function functionOne() {
var variableThree = 3;
return variableThree;
}
function functionTwo() {
var variableOne = 1;
var var3 = functionOne();
var result = var3 - variableOne;
console.log(variableOne);
console.log(var3);
console.log('functional result: ' + result);
}
functionTwo();
function function1() {
var a = 1;
localStorage.setItem("var1", a);
alert("Function1 value of a: " + a);
}
function function2() {
var a = localStorage.getItem("var1");
alert("Function2 value of a: " + a);
}
<!-- first declare the variable -->
<script>
var x;
function something(){
var x = document.getElementById('hello').innerHTML
}
function other(){
document.write(x);
`you can use x here x is same as document.getElementById('hello').innerHTML`
}
</script>