-6

Edit 3 years later: I simply forgot to call the function.


So i have this code:

function xy () {
   return true
}

Can I now read the return in an if statement? I tried this, but it didn't work.

if (xy == true){
  //stuff
}
Max
  • 965
  • 1
  • 10
  • 28
  • After being declared `xy` will return the actual function. `xy()` will run it and give you the value returned. – BenShelton Apr 29 '17 at 11:13
  • while returning a boolean value or just a truthy or falsy value, you do not need to check against a boolean value. just `if (xy()) { /* stuff */ }` is sufficient. – Nina Scholz Apr 29 '17 at 11:16

2 Answers2

3

You need to call your method to retrieve the result.

if(xy() === true){
  //stuff
}
Karl-Johan Sjögren
  • 16,544
  • 7
  • 59
  • 68
  • ok, i tried that and it works. But when I'm using it in my code (https://jsfiddle.net/jfw20w87/2/) it just returns an "undefined" can you help me there? – Max Apr 29 '17 at 13:31
  • You need to read up on asynchronous calls and callbacks in javascript. There is a good thread on it here: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call Also, if you need to use the result of a function in several comparisons you should store the result in a variable and compare with that or else your function will be called for each comparison. – Karl-Johan Sjögren Apr 29 '17 at 14:20
3

You need to call the function:

if (xy() == true){

Writing xy just references the function and the function object is not equal to true

idmean
  • 14,540
  • 9
  • 54
  • 83