1

I have two file a.js and b.js, I need to return value from a.js. This is the program which I wrote, please correct it thanks!

a.js

var a = (function(){
   var some = function(aa) {
        aa + 10;
   }
   var init = function(aa) {
      some(aa);
   }
   return {
       init : init
   }
})();

b.js

console.log(a.init(5));
9
  • So what exactly is the problem? are you using nodejs, a html or ...? what doesn't work? what should be corrected? Commented Dec 16, 2018 at 13:58
  • Assigning a self-invoking anonymous function to a variable? Why? Commented Dec 16, 2018 at 13:59
  • I'm getting undefined when i log the result. Commented Dec 16, 2018 at 14:01
  • @kinduser I need to acces another file thats why Commented Dec 16, 2018 at 14:03
  • 2
    You need to return something in your some function. change it to return aa + 10. also your init function, to return some( aa ) Commented Dec 16, 2018 at 14:04

1 Answer 1

1

It's a chain. three functions are calling here:

  1. call init from b.js: a.init( 5 )
  2. call init from a.js: init = function( aa ) { ... }
  3. call some from a.js: some = function( aa ) { ... }

every function return undefined by default, so if u want to pass your calculated value through all of this, you need to return it in every function.

new a.js

var a = (function(){

    var some = function(aa) {
        return aa + 10;
    }

    var init = function(aa) {
       return some(aa);
    }

    return {
        init : init
    }

})();

now call your b.js file, and it will work as expected.

Update:

if you would like to get rid of those return values, you can use arrow-functions like this:

var a = (function(){

    var some = aa => aa + 10;

    var init = aa => some(aa);

    return {
        init : init
    }

})();

they will return calculated value by default ( instead of undefined ).

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

5 Comments

why I want to write three return, is there is a any short cut?
Only if you use ES6 arrow function syntax
@enf0rcer how to write short cut in es6?
@Rijo Actually, there is. but you need to use ES6 ( a.k.a. JS2 ) syntax. check updated answer.
I see @mrReiha already updated his answer. In the above example you can actually get rid of the entire init function. just use some function directly. That will save you some extra code. No need create a wrapper function for that as you only communicate via a.init method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.