简体   繁体   中英

Function returns correct value and 'undefined'

I have following code:

module = {

        submodule: {

            value: 'foo',

            init: function(){
                console.log(module.submodule.value);
            }

        }

    };

When I'm testing this code through console I get correct value and undefined but when I'm using same code with return statement inside init function I only get correct value. I suppose this is one of those common beginner and trivial questions but I currently can't wrap my head around this :)

Console return undefined because your method doesn't return any value and the console always output the return of a function when called from the console.

If you add return true in your init method it will output the value and true.

It's only the behaviour of the console you are seeing nothing wrong.

Your function isn't returning anything. THe console only displays the returned value of the function. There is no need for your function to return something, but if you want the console to finally show "value", then use

module = {

        submodule: {

            value: 'foo',

            init: function(){
                return module.submodule.value;
            }

        }

    };

What happens is that each function "returns" something. This something can be used as inputs elsewhere. For example,

function getName(){
return "Manish";
}

alert(getName()) //will display "Manish" sans quotes

You can do stuff like

function sin(theta){
//do some math voodoo, store result in "result"
return result;
}
alert((sin(theta)*sin(theta)-5)/Math.sqrt(1-sin(theta)*sin(theta))//random thingy

But, if you decide to not let your function return something (or use return; since it can immediately exit the function), it will return an undefined value, since, well, you didn't define what you wanted it to return . WHich is fine, as long as you don't try to use the returned value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM