Return function not using variables - javascript

Basically, I want to organize my code better by creating function definitions wherever I can. When I try to create a new function outside the current scope and return that, it will say x and y are not defined.
I know it's definitely something to do with scoping. Is there anything I can do to organize my code like in the 2nd code paragraph below? Or do I have to declare my functions in the right scope.
# Works
function RandomFunction() {
x = 1;
y = 1;
marker.addEventListener('click', function(x, y) {
return function() {
console.log(x+y);
}
}
}
# Not working
function RandomFunction() {
x = 1;
y = 1;
marker.addEventListener('click', function(x, y) {
return add;
}
}
function add() {
console.log(x+y);
}

The function add needs to have each number passed in as parameters(firstNum, secondNum).
The function RandomFunction can declare x and y as variables above the event listener scope. Then when the click event is activated, x and y from the RandomFunction scope will be passed to the add function where the add function can reference those values as firstNum and secondNum.
Also, there is no need to return the function "add" within the click event's callback function.
function RandomFunction() {
var x = 1;
var y = 1;
marker.addEventListener('click', function() {
add(x, y);
});
}
function add(firstNum, secondNum) {
console.log(firstNum + secondNum);
}
RandomFunction();

I am not sure what you want to accomplish, but if you want to return a function that "sees" your x,y and can operate on them here it is :
function RandomFunction() {
var x = 1;
var y = 1;
marker.addEventListener('click', function() {
// (add(x, y))(); this will give you 2 in console
return add(x, y); // this will return a function that when you execute it will give 2 as result
})
}
function add(x, y) {
return function() {
console.log(x + y);
}
}
RandomFunction();
I am not sure what you want to do, but this will return a function that has access to your x,y when marker is clicked.

Related

How do you add multiple arguments from different functions into one function containing all the parameters?

Is this possible in JavaScript
I am curious, if I set up three parameters in one function, can I pass the arguments independently in three different functions?
For example, if I created a function that calculates three parameters like the one below, can I then just pass an argument for each of these parameters x, y and z in three different functions.
I understand the example code is not a very good example but its the only way I could think up a explanation.
Main function
function mathsCal(x, y, z) {
return (x * y) - z;
}
The three independent functions
function one(x) {
return x = 23;
}
function two(y) {
return x = 19;
}
function three(z) {
return x = 45;
}
You can do something like this for example you have your 3 functions, each of them receive 1 parameter
function num1(param) {
//your code for num1, return a value
return param
}
function num2(param) {
//your code for num2, return a value
return param
}
function num3(param) {
//your code for num3, return a value
return param
}
Then you can call them all inside single function that will receive all 3 parameters needed for num1, num2 and num3
function sumNum(x, y, z) {
var value1 = num1(x);
var value2 = num1(y);
var value3 = num1(z);
return (value1 * value2) + value3;
}
Then call your function with the needed parameters
var result = sumNum(1,2,3)
console.log(result);//your output = 5
Without using JQuery and using the code I got from user "Chris G", I believe this is the best answer to my question. Please leave comments if I have written this wrong so I can correct it.
<button id= "btn">Get Answer</button>
var numVal1 = 2;
var numVal2 = 6;
var numVal3 = 9;
document.getElementById("btn").addEventListener("click", function() {
funcPara(numVal1, numVal2, numVal3);
})
function funcPara(x, y, z) {
num1(x);
num2(y);
num3(z);
}
function num1(para) {
console.log(`num1 = ${para}`);
}
function num2(para) {
console.log(`num2 = ${para}`);
}
function num3(para) {
console.log(`num3 = ${para}`);
}

How to make the return variable hold a new value after Increment/Decrementing it in a function?

Everytime I run this function, the p1_Balance will always reset back to 10 and will not hold the new value of an increment or decrement.
function Balance() {
var p1_Balance=10;
var x= Math.floor(10*Math.random());
if (x<5) {
p1_Balance=p1_Balance-1;
} else {
p1_Balance=p1_Balance+1;
}
return p1_Balance;
}
Pass p1_Balance into the function instead of initializing it each time the function is called with: var p1_Balance = 10;
p1_Balance should be declared outside the scope of the function (meaning not within the function itself). Otherwise, each time the function is called, the initializer that sets the value to 10 runs as well.
var p1_Balance=10;
function Balance(){ ...
You can use Javascript closures to create a function that does what you want, as you can see below:
var Balance = (function() {
var p1_Balance = 10;
return function() {
var x = Math.floor(10 * Math.random());
if (x < 5)
return p1_Balance += 1;
else
return p1_Balance -= 1;
};
})();
for (var i = 0; i < 10; i++)
console.log(Balance());
Alternatively, you will need to define the p1_Balance variable outside the function or pass it as an argument.
There could be several solutions:
one is declaring p1_Balance as a global variable.
var p1_Balance=10;
function Balance(){
var x= Math.floor(10*Math.random());
if (x<5) {
p1_Balance=p1_Balance-1;
}
else {
p1_Balance=p1_Balance+1;
}
return p1_Balance;
}
another is you could pass balance as a function parameter:
function Balance(p1_Balance){
var x= Math.floor(10*Math.random());
if (x<5) {
p1_Balance=p1_Balance-1;
}
else {
p1_Balance=p1_Balance+1;
}
return p1_Balance;
}
.....
value = Balance(10);// value=something that you want to change by that function.

Object function scope

factory(n) returns objects with functions.
func1 function definition creates its own scope, and x inside this function references x = n + ''.
But func2 is a reference and the scope is wrong.
Is there a way to return an object from create so its functions were references (not separate definitions)?
Actually, I'm fine with func1 approach while function definition footprint is small. If it is a complex function it would be better not to clone this function into every object comming from factory(n). inner_func may not use this, it is simple function. Also I want to avoid new and this.
var factory = (function(){
var x = '!';
return function create(n){
var x = n + '';
return {
func1: function(y){return inner_func(x, y); },
/* vs */
func2: inner_func_api
}
}
function inner_func_api(y){ return inner_func(x, y); }
function inner_func(a, b){ return a + b; }
}());
var f1 = factory(2);
var f2 = factory(3);
var f1_func1 = f1.func1(4);
var f2_func1 = f2.func1(5);
var f1_func2 = f1.func2(4);
var f2_func2 = f2.func2(5);
console.log(f1_func1, f2_func1); //24 35
console.log(f1_func2, f2_func2); //!4 !5
You could define that function separately from the object initializer on the return statement:
var factory = (function(){
var x = '!';
return function create(n){
var x = n + '';
function func1(y) {
return inner_func(x, y);
}
return {
func1: func1,
/* vs */
func2: inner_func_api
}
}
function inner_func_api(y){ return inner_func(x, y); }
function inner_func(a, b){ return a + b; }
}());
However, it makes no practical difference, and it doesn't matter how big or complicated that function is. Function instances do take up space, but the code for the function is constant (immutable) and doesn't need to be part of every Function object created from the same piece of source code.

how can i implement this logic add(1)(2)(1).. upto (n)?

I know this question is already answered with limited capability but I want it with n number of time with n arguments?
function add(x) {
return function(y) {
if (typeof y !== 'undefined') {
x = x + y;
return arguments.callee;
} else {
return x;
}
};
}
add(1)(2)(3)(); //6
add(1)(1)(1)(1)(1)(1)(); //6
problem is this works only when I add extra empty brackets ()
it doesn't work if do this add(1)(2)(3)
reference question
Try this:
function add(x) {
var fn = function(y) {
x = x + y;
return arguments.callee;
};
fn.toString = function(){ return x; };
return fn;
}
The following code works exactly like you asked:
function add(a)
{
var c=a,b=function(d){c+=d;return arguments.callee;};
b.toString=function(){return c;}return b;
}
Do note that some operations will detect the result given as a function, but any functions that require a string or integer will see the proper value.
Try sending your numbers as an array and changing your function code to reflect these changes.
Note: Code untested.
function add(x) {
var result = 0;
for (i = 0; i < x.length;i++){
result+=x[i];
}
return result;
}
add(new Array(1,2,3));

Purpose of multiple assignment var x = this.x = function(){}?

In Mootools the following pattern occurs frequently:
var x = this.x = function(){}
For example:
var typeOf = this.typeOf = function(item){ ...
I understand multiple assignment results in function being assigned to both x and this.x. But I thought in the global scope x is implicitly this.x, so it seems redundant. Is this an optimization technique, or is there some other purpose to this pattern?
This is only redundant if this code isn't executed in a function.
If it's in a function, the var is local, even if the context (this) is the global one.
Look at this :
function a() {
var x = 1;
console.log(x)
}
function b() {
console.log(x); // fails
}
a();
b();
If you want to be both able to use x directly in a and have this.x in b, then you need the double assignation :
var x = this.x = 1;
I frequently use this pattern in big functions when I have a variable I use a lot and for which I prefer a direct access without this..
var x is not equals this.x, var x is a varible private of a js class and this.x is a public propertie, so the code create 2 ways for invoke a function
Here an example:
function exampleA() {
this.x = 1;
var x = 2;
this.show = function () {
alert("A.x:" + x);
alert("A.this.x:" + this.x);
};
}
function exampleB() {
var x = this.x = 1;
this.x +=1;
this.show = function () {
alert("B.x:" + x);
alert("B.this.x:" + this.x);
};
}
$(document).ready(
function () {
var example1 = new exampleA();
example1.show();
var example1 = new exampleB();
example1.show();
});

Categories