JS Module : Difference between directly returning a function in an object and returning a function in an object returning a function

Viewed 30

It's redundant but I am learning JS and I want to know how it really works.

  1. Returning a function directly from a module
let func1 = function () {
    let test = function () {
        console.log("1");
    }
    return {
        getTest : test
    }
}
  1. Returning a function by using a function
let func1 = function () {
    let test = function () {
        console.log("1");
    }
    return {
        getTest : function () {
            return test;
        }
    }
}
1 Answers

In the first case, the getTest property of your object points to a function, so calling it this way:

func1().getTest()

Should result in logging 1.

In the second case, getTest returns a function which returns another function, so you'd have to also call the result in order to get 1, this way:

func1().getTest()();

Calling just getTest will return your function object, rather than calling it.

Related