Function not returning as expected

Hey Campers,

I am having an issue with functions returning something other that the value I expect. Below are two examples. The first one I am actually using, the second just as a test. Instead of returning a value when I console.log, it returns the name of the function.

In the second example, when I try to add 1 to the returned value of “test”, it shows the full text of the function with a 1 at the end, like it is a string somehow.

Any idea why this is happening?

  var currentID = function(){
    for(pi of paintings){
      if(pi.img === closeupPic.img.src) return pi.id
    }
  }
  console.log(currentID)

CONSOLE:
function currentID()

  var test = function(){
    return 99
  }
console.log(test)

CONSOLE:
function test()

  test += 1
  console.log(test)

CONSOLE:
function(){
return 99
}1

The reason the first code example does not return a value like a string or number, is because you are not calling the function currentID.

Write:

console.log( currentID() );

and you will get something other than the function itself.

You have a similar issue with the second code example. You are not calling the function named test. Also, when you write:

test += 1;

You are concatenating 1 to test and then reassigning the result to test, so JavaScript coerces the function into a string first and then appends the 1 to the end.
So when you write:

console.log(test);

you are displaying the following string:

"function() {
  return 99
}1"
1 Like

Thank you as always, Randell.