eaglei22
eaglei22

Reputation: 2830

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.
}

Upvotes: 0

Views: 894

Answers (2)

Nick
Nick

Reputation: 106

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!"

Upvotes: 1

beta-developper
beta-developper

Reputation: 1774

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);

Upvotes: 1

Related Questions