skip to Main Content

enter image description here
enter image description here

It looks like you are calling a function and storing the call to that function in a variable.
Why are the outcome different?????

I thought the results would be the same, why are they different?

5

Answers


  1. createCount() returns function and count() returns value because count is a function that is returned by createCount().

    Login or Signup to reply.
  2. Remember that createCount returns a function object. So this:

    console.log(createCount())
    

    Just prints the function object. It does not CALL the function that was returned. Where as this:

    count = createCount()
    console.log(count())
    

    Stores the function object, and then CALLS that function object. Two very different operations.

    It’s like the difference between these two:

    console.log(Math.random);
    console.log(Math.random());
    
    Login or Signup to reply.
  3. I’ll give you some code that makes intuitive sense.

    The code above is like

    console.log(function() {
        return a += 1 // a = 0 at first
    }())
    

    The code below is like

    console.log(function() {
        let a = 0
        return function() {
           return a += 1
        }
    }())
    
    Login or Signup to reply.
  4. As you indicate this is an example of closures where a function has access to values in the outer scope, as long as they aren’t shaded by other functions.

    I think this example is a lot simpler to get a first understanding:

    function fullName(name){
      const surname = "aerial";
      return (name) => `${name} ${surname}`
    }
    

    So surname is already replaced.

    You could also use other variables form the outer scope like process.env.SURNAME in a NodeJS process.

    Login or Signup to reply.
  5. Look at this code…

    function createCount() 
      {
      let a = 0;
      return function (txt)
        {
        return `${txt} -> ${++a}`
        }
      }  
    const 
      countA = createCount()
    , countB = createCount()
      ;
    console.log( countA('A') );
    console.log( countA('A') );
    console.log( countA('A') );
    console.log( '------' );
    console.log( countB('B') );
    console.log( countB('B') );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search