function celebrityName(firstName){
var nameIntro = "This celebrity is ";
function lastName(theLastName){
return nameIntro+firstName+" "+theLastName;
}
return lastName;
}
var mjName= celebrityName("Michael");
mjName("Jackson");
I understand that the purpose of this code is just to output: “This celebrity is Michael Jackson” There are a few things that got me confused.
- The 1st name “Michael” is being passed through
celebrityName()
that I can understand. The parameter is being submitted into the function. Like x+y=2, and you submit x=1. But the question is when was time thatlastName
got submitted into the function?
And let’s say that I have another set of code here:
var nameIntro = "My full name is ";
var firstName = "Kay";
var lastName = "Adam";
function spellName(){
console.log(nameIntro+firstName+lastName);
}
spellName();
The difference between this 1st set code and my code is that he used function lastName
to produce the whole sentence while I use the function spellName()
to produce the whole sentence. Am I correct?
- Why is the last name “Jackson” got subbed into
mjName
instead of functionlastName
, it only causes more confusion isn’t it? You’ve already assigned a value to the variablemjName
and now you interchange it again? Why?
Could someone explain to me all these? The bottom line is I don’t understand why those code can produce the sentence “The celebrity is michael jackson”. And if I am the one who write this code, I will write it more clearer than the author.
BTW, I found this code from this website that is explaining what is javascript closure.