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 ?

0

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.