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
Related
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!"
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
Why isn't this working as expected?
function external() {
function internal() {
alert("external");
}
return internal;
}
external(); //nothing happens
var func = external();
func(); // alert pops up
does it have to do with the fact, that it's a closure? Because here it works like I expect it would:
function test() {
alert("test");
}
test(); //alert pops up without assigning the function to a variable
like #thefourtheye suggested when i just do
external();
only the internel function object gets returned.
I just added an example to make it more clear!
function external() {
alert("foo");
function internal() {
alert("bar");
}
return internal;
}
external(); //returns foo (and the internel function)
external()(); //return foo and then bar
When you return internal, it is returning a function. The function is NOT executed, merely passed as a reference back to the caller of the external function. So external() basically evaluates to a function expression that is not executed. It is effectively equivalent to writing:
function() {
alert("external");
}
Nothing happens, because the function is simply expressed but never executed.
Contrastingly, for var func = external();, the function expression is assigned to variable func. In effect, it is equivalent to writing:
var func = function() {
alert("external");
}
This is why when you execute func() subsequently, the alert pops up.
so a simple example would be
function a() {
alert("something");
}
anything.onclick = a; // this is without parentheses
anything.onclick = a(); // this is with parentheses
What is the difference between the two?
And one thing more: if I define the same function but this time return false, will it work?
function a(){
alert("something");
return false;
}
The difference is that a() calls the function while a is the function.
console.log( a() ); // false
console.log( a ); // function() {...}
To make it clear what technically happens when you use the second part of your example, let's redefine alike this:
a = function() {
return 100;
};
and set the event handler:
anything.onclick = a();
f() not only calls the function f but returns its return value. So when setting a variable or object property to a function call, the return value of the function call will be assigned. So the above statement is effectlively equivalent to:
anything.onclick = 100;
which doesn't make sense and might cause an error. If a function doesn't have a return value, its return value is implicitly undefined.
However, if you had set a variable equal to a without calling it, it would be the same as setting a regular function expression to that variable:
var a = function() { ... },
b = a; // b = function() { ... }
b would perform the same operation as a would.
So in your example go with the first one because it makes sense! The only case in which you would assign the return value of the function call to an event handler is if the function returns another function. For instance:
var x = function(xyz) {
return function() {
console.log(xyz);
};
};
anything.onclick = x("Hello World"); // = function() {
// console.log("Hello World");
// }
Assigns reference:
anything.onclick = a; //assigns a reference
With your function it is:
anything.onclick = function() {
alert("something");
}
Executes method and assigns the returned result
anything.onclick = a(); //calls the method and assigns whatever is returned.
With your function it is:
anything.onclick = false;
The parenthesis at the end of the function is the permission for javascript engine to execute the function. If you don't supply it, it won't be executed at all.
If you do x=a() you are invoking the function but if you do x=a you are passing a pointer to a function
long story short:
Let's say we have
function f(){} or f = function(){}
If you now write
someFunction(f());
it will call f() and whatever f() returns will be passed as argument to someFunction().
If you write
someFunction(f);
on the other hand (when defined like the latter), f will be passed to someFunction() as (a variable holding) the function.
This could be used e.g. if the function is supposed to be used later on but maybe can't be called some other ('normal') way.
( Of course, depending on language, "function" could obviously be a "method" and the language could not even have function-variables or however you call it! )
( off topic: note that this answer says the same as the other answers because that is THE true answer but I did not want to edit the other answers because each may be found differently helpful by different people )
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>