Training Days - parameters

Hello! I’m stuck on this exercise https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-scope/projects/training-days because I am missing something.

Task number 5 says:
The log functions– logEvent() and logTime() –use the same name variable. There seems to be a problem with the scoping; we can tell by the amount of duplicate code here! In addition to variables scoped too broadly, duplicate code can indicate that a variable may be scoped too tightly.

Let’s avoid this repetition by adding name as the first parameter for each function.

Why should I have to add name as the first parameter? Maybe it’s easy but I still don’t get it.

Thanks for your help.

I don’t have a pro account so I can’t say for sure, but it may be that both functions are using the same generated variable, name.

Instead of doing this one could have a global variable name and use that as a function parameter.

Here is an example:

let name = 'Tommy';

function ask(name){
    console.log('Where is ' + name);
};

function talkAbout(name){
    console.log('Did you know ' + name + ' likes carrots?');
};
3 Likes

To begin with, you have two functions - logEvent() and logTime() - which each take a single parameter, event and days respectively.

Both of these contain a block-scoped variable, name, which has the value "Nala".

Generally speaking, repeating oneself unnecessarily when coding is a bad thing - for example, if we need to change the name of the athlete then we need to change it in two places.

By making name a global variable, we make it accessible everywhere rather than only inside the function where it was before, so we only need to change it in one place.

By adding a parameter to each of the functions, we can pass in the appropriate value for name without needing to define it inside the function.

Does that make sense?

2 Likes

Thank you @8-bitgaming your answer is really helpful to me.

2 Likes

Thank you @thepitycoder our answer is really helpful to me.

1 Like