'In javascript, why is this showing when I console.log but not when I return

Fairly new to Javascript, so try not to attack too much :). Here's the challenge I'm trying to solve. When I console.log it, it returns what I'm looking for, but when I replace console.log with return, it doesn't return anything. Can someone help clarify? Thank you.

My challenge is:

Write a function, callTimes, that returns a new function. The new function should return the number of times it’s been called.

function callTimes() {
  let count = 0;
  return function inner(){
    count++;
    console.log(count)
  }
  return inner
}

let myNewFunc1 = callTimes();
let myNewFunc2 = callTimes();
myNewFunc1(); // => 1
myNewFunc1(); // => 2
myNewFunc2(); // => 1
myNewFunc2(); // => 2

If I do the same thing but replace console.log with return, it doesn't return anything. Trying to figure out why:

function callTimes() {
  let count = 0;
  return function inner(){
    count++;
    return count
  }
  return inner
}

let myNewFunc1 = callTimes();
let myNewFunc2 = callTimes();
myNewFunc1(); // => 1
myNewFunc1(); // => 2
myNewFunc2(); // => 1
myNewFunc2(); // => 2
//Output should be the same as above... 
//but nothing logged


Solution 1:[1]

In your second example, the numbers are returned correctly, but they didn't show up in the console.

That's because return does not log anything. return is the part of the language, not a debugger tool.

When you return something, that value goes back to the caller and allow it to perform more operations with the value, e.g. doing math, storing to variable, passing to another functions, calling (like how you did in case of the function returned from callTimes())...

So, to see those values in the console, log them after they're returned:

function callTimes() {
  let count = 0;
  return function inner(){
    count++;
    return count //<--Return instead of logging
  }
  return inner
}

let myNewFunc1 = callTimes();
let myNewFunc2 = callTimes();
//Log the returned values
console.log(myNewFunc1()); // => 1
console.log(myNewFunc1()); // => 2
console.log(myNewFunc2()); // => 1
console.log(myNewFunc2()); // => 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1