Following is my code snippet :
function executorFunc(input){
return input();
}
function mainFunc(){
var a = 100;
function innerFunc(){
var b = 20;
return a + b;
}
executorFunc(innerFunc);
}
var finalVal = mainFunc();
console.log(finalVal);
I was in the assumption that innerFunc gets created within mainFunc and will be aware of outer/enclosing functions data like a = 100. To my surprise, it's not. There is something that is doing it wrong or there is something which I have misunderstood in basics of JS.
The final output is undefined where I was expecting 120.
Expected result as you are not returning the value from mainFunc function().
Use
return executorFunc(innerFunc);
function executorFunc(input){
return input();
}
function mainFunc(){
var a = 100;
function innerFunc(){
var b = 20;
return a + b;
}
return executorFunc(innerFunc);
}
var finalVal = mainFunc();
console.log(finalVal);
The problem here is that mainFunc does not return any value. So finalVal remains undefined.
Related
I have a function which takes in a String. The function checks if the object in the list has this function(functionName). If it contains that function, how can I return it? Obviously, return list[i].message would work, but thats not what im after. I want do use the parameter functionName in this case.
function message(){
return "hello";
}
function test(functionName);
listLength = list.length;
for(i = 0; i < listLength; i++){
if(list[i].hasOwnProperty(functionName}{
return (?)
}
}
var x = test("message");
alert(x);
Grateful for response
the comment from Pointy is right, but you have to consider that having a function detached by its owner will screw the scope, so you will no longer have access to the right this object
var test = {
number: 0,
testFunction: function() {
return this.number;
}
}
console.log(test.testFunction()); // output: 0
var x = test.testFunction;
console.log(x()); // output: undefined
maybe you should use
var y = test.testFunction.bind(test);
console.log(y()); // output: 0
JS Bin example
Why does it not count, my output is always 1 in the console. I am new to closures and I must be missing something simple? Here is the code from the jsbin:
var counterFunc = function()
{
var count = 0;
var incCount = function()
{
count = count + 1;
return count;
};
return incCount();
};
var myCounter = counterFunc;
console.log(myCounter());
console.log(myCounter());
By returning incCount() - the result of the invocation - from your counterFunc, you're not really creating a closure function. You want to return a function, and invoke the counterFunc() to create it:
var counterFunc = function() {
var count = 0;
var incCount = function() {
count = count + 1;
return count;
};
return incCount ;
// ^
};
var myCounter = counterFunc();
// ^^
console.log(myCounter());
console.log(myCounter());
You should be returning the inner function itself, not the result of calling it
You therefore need to replace return incCount() with:
return incCount;
You subsequently need to directly invoke counterFunc() when you declare myCounter:
var myCounter = counterFunc(); // myCounter is now the closure
Only then will myCounter be assigned a reference to the inner function, that happens to hold a "closure" over the local variable count.
I can't seem to figure out how to get at the return value of a generator - anyone know what I am doing wrong?
function getGeneratorReturn() {
var generator = runGenerator();
var generatorReturn = null;
var done = false;
while(!done) {
var currentNext = generator.next();
console.log('Current next:', currentNext);
generatorReturn = currentNext.value;
done = currentNext.done;
}
return generatorReturn;
}
function* runGenerator() {
var a = yield 1;
var b = yield 2;
var c = a + b;
return c;
}
var generatorReturn = getGeneratorReturn();
console.log(generatorReturn); // Should output 3, is outputting NaN
Note: You'll need node 0.11.12 running with the --harmony option for this code to run.
When currentNext.done is true, curentNext.value has the return value.
You can write your loop as:
var next;
while (!(next = generator.next()).done) {
var yieldedValue = next.value;
}
var returnValue = next.value;
It seems to work by passing the current value back into the generator when I call .next:
function getGeneratorReturn() {
var generator = runGenerator();
var generatorReturn = null;
var done = false;
while(!done) {
var currentNext = generator.next(generatorReturn);
console.log('Current next:', currentNext);
generatorReturn = currentNext.value;
done = currentNext.done;
}
return generatorReturn;
}
function* runGenerator() {
var a = yield 1;
var b = yield 2;
var c = a + b;
return c;
}
var generatorReturn = getGeneratorReturn();
console.log(generatorReturn); // Should output 3, is outputting NaN
Note: You'll need node 0.11.12 running with the --harmony option for this code to run.
A generator function CANNOT return a value.
Instead, a generator function automagically gets wrapped by an Iterator instance which gets returned.
Because a generator function is always executed asynchronously (triggered by yield statements or even by injecting values manually using Iterator.next( value) - see this example ) the return statement can only be used to "close" the returned Iterator somewhere in your generator function code.
You can only "return" values from a generator function using yield.
I have a function that replaces characters from a string
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/\./g, ', ');
var final = "[[" + s + "]]";
alert(final);
}
What I need is to get the value of final outside the function like this:
var outsideValue = final;
EDIT!!! --
function ratko() gets it's value from ajax
success: function (data) {
if (data.success) {
alert("Note: This month has " + data.holidays.length + " holidays.");
praznici = data.holidays;
ratko(praznici);
}
else {
alert(data.ErrorMessage);
}
Possibility 1:
function ratko (a) {
...
return final;
}
var outsideValue = ratko (...);
Possibility 2:
var final;
function ratko (a) {
// no var final declaration here
...
}
...
ratko (...);
// now final has the value assigned to it in the function
You can access variables declared in an outer scope in an inner scope, which is what you do in Possibility 2.
One option would be to use a global variable, just declare it outside of the function.
var myvar = 1;
function myFunction()
alert(myvar); // 1
}
You can read more on javascript variables here.
You declare it outside the function scope:
var finalVar;
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/./g, ', ');
finalVar= "[[" + s + "]]";
alert(finalVar);
}
var outsideValue = finalVar;
Beware final is a reserved keyword in Javascript. I changed its name.
Besides that, keep in mind that Javascript is always parsed from top to bottom. So using a variable before declaring it will definitely give you an undefined.
you must be modify your function code like this
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/./g, ', ');
var final = "[[" + s + "]]";
//alert(final); comment this code line and replace this with the code above
return final;
}
after you can call your function ratko with this simple code
var inputValue = 'simple message';
var parsedValue = ratko(inputValue);
you find the final value into a new variable parsedValue
If I have a function, like this:
function f(x,y){
return x + y;
}
And if I have variables of parameters I want passed to f:
var parameter1;
var parameter2;
If I assign this function call to a variable:
var functionCallValue = f(parameter1,parameter2);
How can I ensure that functionCallValue changes depending on different values I assign to the variable parameter1 and parameter2?
I suppose what you need is a closure.
var servant = function(x, y) { return x + y; };
var param1 = 40;
var param2 = 2;
var master = function() { return servant(param1, param2) };
var result = master(); // 42.
param1 = 2;
param2 = 40;
var anotherResult = master(); // still 42, because that's really the answer!
functionCallValue is assigned the result (returnvalue) of your function f. (The function is called, the value calculated and the result handed over to your variable.) Thus functionCallValue does not automatically update, if you change the parameters (which would make no sense at all), you need to call the function again with the altered parameters.
For something like an auto-update you need a closure like this:
var asdf = (function(){
var param1 = 1;
var param2 = 2;
var result = param1+param2;
function compute(){
result = param1 + param2;
}
return{
param1:function(x){
param1 = x;
compute();
},
param2:function(x){
param2 = x;
compute();
},
result:function(){
return result;
}
}
})();
console.log(asdf.result()); // logs 3
asdf.param1(3);
console.log(asdf.result()); // logs 5
Demo