Jump to content

How to understand these specific lines of code. (javascript)

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.

  1. 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 that lastName 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?

  1. Why is the last name “Jackson” got subbed into mjName instead of function lastName, it only causes more confusion isn’t it? You’ve already assigned a value to the variable mjName 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.

 

http://javascriptissexy.com/understand-javascript-closures-with-ease/

If it is not broken, let's fix till it is. 

Link to post
Share on other sites

23 hours ago, Erik Sieghart said:

 

yeah! but I love it! i love reading through YDKJS series and getting all the nitty gritty things in straight. as it helps me understand js better, not just writing it. 

23 hours ago, crashahotrod said:

This is a classic example of functions returning functions you can read more about this here https://stackoverflow.com/questions/7629891/functions-that-return-a-function-javascript

Thanks I will look into it later! 

 

Also for everyone else who is interested, here is the original link and it has some pretty good answer there! 

https://forum.freecodecamp.org/t/how-to-understand-these-specific-lines-of-code/149096

If it is not broken, let's fix till it is. 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×