taking variables from one function to use in another function - javascript

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>

Related

How to point already declared javascript function to a variable

If I wanted to first declare a function, and then at some point I want to reference the function and not its return value to a variable, how would I do that?
var best = bestPresidentEver;
function bestPresidentEver(a,b){
//for some reason always returns Trump.
}
and then call best(a,b) instead of bestPresidentEver(a,b)
I am wondering how to do that opposed to assigning the function to the var upon declaration.
var best =
function bestPresidentEver(a,b){
//for some reason always returns Trump.
}
Declare your variable like this
var bestPresidentEver= function (a,b){
//for some reason always returns Trump.
return "Trump"; //:D
}
Then call that function like this
//You have to declare a and b variables
var trumpHere = bestPresidentEver(a,b);
If your function is already declared, just assign it to the variable :
function bestPresidentEver (a,b){
//for some reason always returns Trump.
return "Trump"; //:D
}
var trumpHere = bestPresidentEver;
Then call it like this :
var trumpAgain = trumpHere(a, b);
If the variable exists and it's not a const you can simply reassign it's value to the function itself.
Ex
var foo = 'foo';
function bar(a) {
return 'example ' + a;
}
bar('code'); //=> "example code"
/* Further down, reassign the `foo` variable */
foo = bar;
foo('code, again'); //=> "example code, again"
I am using SignalR, and I need to point it to a function, and I also want to call that function in other areas of the application.
If the library expects a function parameter, you can simply pass that function like so.
function first(next /* expects a function parameter */) {
return next('hello');
}
function second(prefix) {
return prefix+ ' world!';
}
first(second); //=> "hello world!"

What does function in function do exactly in nodejs?

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.

Confusing function in javascript functional programming

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

How to convert text to a function using JavaScript

I have a text string that is correctly formatted as a function and I would like to convert it to an actual function. The text string looks like:
function object_123(){
object_123_Action();
my_clicked(obj);
}
Apart from the word "function" and {}; all other text is dynamically constructed. i.e. It may never contain object_123_Action(), however, it will be something similar, basic function calls. The only issue will be the obj will need to be the object that the function is assigned to.
Basically, I need:
this.func = eval(func_txt); //to actually work.
Where func_txt is:
function object_123(){
object_123_Action();
my_clicked(this);
}
Your string contains a function declaration.
When evaluated, it creates a object_123 variable in the scope of eval (which you can then call later) and returns nothing.
If you want to assign the function to this.func then you need to convert the declaration into a function expression. You can do that by wrapping it in parens.
this.func = eval("(" + func_txt ")" );
var func_txt = "function object_123(){\
object_123_Action();\
my_clicked(obj);\
}";
this.func = eval("(" + func_txt + ")");
var obj = "...";
function object_123_Action() {
alert(1);
}
function my_clicked() {
alert(2);
}
this.func();
You can store your functions in an array on the object.
Then, loop though the functions in another function and execute them.
var myObj = { 'myfunctions': [ ] };
and to add functions:
myObj.myFunctions.push (function () { /*function code here*/ });
Or if you already have a named function:
myObj.myFunctions.push (nameOfFunction);
And to call all the functions, use this function (don't add this function to myObj)
function executeMyFunctions (myObj) {
for (var i = 0; i < myObj.myFunctions.length; i++) {
myObj.myFunctions[i]();
}
}
And if it's possible to avoid using eval, you should.
Try this:
function parseStringToFunction(func) {
func = func || '(function(){return null;})';
return (new Function('return ' + func)());
};
var stringifyFunction = '(function(a, b) { return a+b; })';
var callStringifyFunction = parseStringToFunction(stringifyFunction)(1, 2);
alert(callStringifyFunction); // results is 3
Also read this out: detail about eval() and new Function()
Try this-
$("<script type='text/javascript'></script>").html(func_txt).insertAfter($("script"));
This works:
assert( eval("(function(a, b) { return a+b; })")(1, 2) == 3 )
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#eval_as_a_string_defining_function_requires_(and)_as_prefix_and_suffix
Simply wrap the function in parens.

How can I call a function from another function in javascript

In JavaScript how to call a function from another function. My function is called Cheese and it alerts a hello cheese by passing it to another variable called X. I am practicing javascript functions.
function cheese() {
return function() {
alert('hello cheese');
};
}
var x = cheese();
alert(x);
Now x is a function so you need to invoke it
var x = cheese();
alert(x());
Also since you want to alert the value returned by x, probably you want to return a value from the inner function instead of calling an alert - other wise first the alert in the inner function will be shown then an alert saying undefined will be shown as the inner function is not returning anything.
function cheese() {
return function() {
return ('hello cheese');
};
}
Demo: Fiddle
To pass a function along, assign it to your variable like so:
function foo() {
alert("hello");
}
var bar = foo;
Then call the function like so:
bar();
When you call cheese(), it returns a function.
So, when you do:
var x = cheese();
x now contains a function reference. When you then do:
alert(x);
you're doing an alert on that function reference (which isn't generally a very interesting thing to do because it doesn't execute that function).
If you wanted to execute that function, you would do this:
function cheese() {
return function() {
alert('hello cheese');
};
}
var x = cheese(); // x now contains the inner function that cheese() returned
x(); // will run the returned function which will execute the alert() in the function

Categories

Resources