Javascript returning a function

Javascript returning a function
0

#1

Hello,

I am learning Javascript. I have completed basic understanding of javascript with a lot of practices. I was learning “closures” but I got confused while playing around with this piece of code. Can someone explain this?

function showname(firstname,lastname){
  var nameintro= "Your name is:   ";

  function makefullname()
  {
    console.log(nameintro + firstname + " " + lastname);
  }

  makefullname();
}

console.log(showname("Michael", "Jackson"));

when I run this, I get
Your name is: Michael Jackson
undefined

Then I commented out the //makefullname(); line. and now I just get “undefined”. Where is that coming from?

  1. How I tried this:
function showname(firstname,lastname){
  var nameintro= "Your name is:   ";

  function makefullname()
  {
    return nameintro + firstname + " " + lastname;
  }

   makefullname();
}

console.log(showname("Michael", "Jackson"));

I thought, I am passing the variables to the outer function. Inner function will “return” the concatenated string when that function is called. I still get “undefined”. why is that?

  1. Now I used this code.
function showname(firstname,lastname){
  var nameintro= "Your name is:   ";

  function makefullname()
  {
    return nameintro + firstname + " " + lastname;
  }

   return makefullname();
}

console.log(showname("Michael", "Jackson"));

This works fine. When I return a function from a function, i thought the receiver will get the function definition. Instead it gets the value returned by the innerfunction that has been called. I am really confused.
Can someone explain. Thanks for your time!

Regards,
RM


#2

If you do not explicitly return a value from a function, then the function will return undefined. The call to makefullname inside showname displays the Your name is: Michael Jackson, but the second console displays the returned value from the showname function, which in this case is undefined for the reasons I explained above.


The answer to this problem is the same as the last example.


If you just want to return the function, then you would write:

 return makefullname;

Unless you were going to assign the returned function to another variable, it does not make much sense to do this. If you wanted to use the result of the makefullname function later, you could assign showname(“Michael”, “Jackson”) to a new variable (function) like:

function showname(firstname,lastname){
  var nameintro= "Your name is:   ";

  function makefullname()
  {
    return nameintro + firstname + " " + lastname;
  }

   return makefullname;
}

var newFunction = showname("Michael", "Jackson");
console.log(newFunction()); // displays Your name is:   Michael Jackson

#3

Fantastic. Thanks a lot for your time!

RM