Logic behind declaring important variables at the end of the code vs. at the start

Hi

I’m practicing scopes (the training day exercise).

in the code provided in the exercise, two important const (event and days) are declared at the end of
the code, even though they are refered to earlier.
why is it? doesn’t it make more sense declaring them before refering to them? and given that the code runs linearly, how does it not cause errors?

i’ve attached the code, hopefully according to post guideline (my first post here)
TIA

const getRandEvent = () => {
  const random = Math.floor(Math.random() * 3);
  if (random === 0) {
    return 'Marathon';
  } else if (random === 1) {
    return 'Triathlon';
  } else if (random === 2) {
    return 'Pentathlon';
  }
};

// The scope of `days` is too tight 
const getTrainingDays = event => {
  let days;
  if (event === 'Marathon') {
     days = 50;
  } else if (event === 'Triathlon') {
     days = 100;
  } else if (event === 'Pentathlon') {
     days = 200;
  }

  return days;
};

// The scope of `name` is too tight 

const name = 'Nala';

const logEvent = (name, event) => {
  console.log(`${name}'s event is: ${event}`);
};

const logTime = (name, days) => {
  console.log(`${name}'s time to train is: ${days} days`);
};

const event = getRandEvent();
const days = getTrainingDays(event);

function parameters like event here:

const getTrainingDays = event => {

have a local scope, they only exists within the function. Parameters act as placeholders until they get there value from argument at function call. You might use event variable name twice, they are different variables with different scopes.

To declare the function first, then call them later and store results of these calls in variables is really common.

not sure I understand…
in this example the paramater event gets a value by calling getRandEvent () at the end of the code.
that value is passed to getTrainingDays () which is above it.
doesnt it make more sense calling const event = getRandEvent() before declaring the function that has event as a parameter?

parameters act as placeholders. They don’t have an actual value. If its confusing, you could give your parameter a different name.

How can you call something you haven’t defined yet?

1 Like

I think i understand. got confused between defining a function and calling it.
thanks!

Are you sure you understand? Can you explain it to me now? If you understand, you should be able to explain :slight_smile:

Didnt see your reply untill now…
I understand that in declairing a function I set up its paramaters and when calling it I pass arguments.
I think I just got confused by the fact the the “name” variable has a value and is what’s starting all the chain reaction where the event paramter becomes an argument through calling the getRandEvent() function.
it was too much information to follow at that time :slight_smile:

So, you understand now?

1 Like