0

var Module = (function() {
    var privateMethod = function() {
        console.log('Private method');
    }
    
    return {
        publicmethod1: function() { console.log('first'); },
        publicmethod2: function() { console.log('second'); }
    }
})();

console.log(Module.publicmethod1());
console.log(Module.publicmethod2());

Completely contrary to my expectation ,i am getting

first
undefined
second
undefined

. What i was expecting is first and then second but not undefined .What is the reason for this undefined ?

Tim Klein
  • 2,538
  • 15
  • 19

2 Answers2

2

Replace

console.log(Module.publicmethod1());
console.log(Module.publicmethod2());

with

Module.publicmethod1();
Module.publicmethod2();

Your public methods already have console.log().

To expand...

The statement Module.publicmethod1() is not returning anything (which means it returns undefined, so when you put that statement in a console.log() call, you're printing the result of that method which is undefined.

Since you are also calling console.log() in your methods, you don't need to print the result of the methods (since they don't return anything anyway).

Tim Klein
  • 2,538
  • 15
  • 19
westdabestdb
  • 4,353
  • 20
  • 28
0

When you run publicmethod1() and publicmethod2(), they already log first and second but they don't return anything. So the last console.log calls will log the return value of the called methods, which is undefined. Just call

Module.publicmethod1();
Module.publicmethod2();

and then you don't get any undefined.

enys
  • 513
  • 3
  • 11