JavaScript Scope

<
// The scope of random is too loose
const random = Math.floor(Math.random() * 3);

const getRandEvent = () => {
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;
};

const name = ‘Nala’;

// The scope of name is too tight
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);
// Define a name variable. Use it as an argument after updating logEvent and logTime

logEvent(event);
logTime(days);

/>

The above is my code. It is from the scoping exercise on JavaScript. In one part of the exercise, it asks us to " Pass name as the first argument to logEvent() and logTime() ." However, when I do this, the following is output:

Why does it change the name to Triatholon, Marathon, or Pentathlon and the event and days become undefined? If I remove the parameters, the code runs fine, but the exercise asks you to add the parameters, so I know it’s supposed to work.

A quick one about code formatting:

You can click the </> icon in the menu bar which appears at the top of the text box while you type.

capture

Press Enter to go to a blank line, click that icon, and you will see this:

capture_r

Just copy and paste your code directly from the editor into that highlighted portion, and the forum will retain the formatting. :slight_smile:

It doesn’t match what’s shown in the screenshot; is it up-to-date? :slight_smile:

In your code, you are calling the functions like so:

logEvent(event);
logTime(days);

In each, you’re providing a single parameter. In the definitions I can see in your screenshot, the functions look like this:

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`);
};

The output you’re getting is correct, for a single parameter input. :slight_smile:

I edited the code part.

1 Like

:+1:

It would appear my explanation of why you’re seeing the output you are was correct. :slight_smile:

Can you see how to fix it? :slight_smile:

Oh so in the bottom, when I call the function, I need to put two parameters?

1 Like

Bingo. :+1:

name and event for logEvent, and name and days for logTime. :slight_smile:

ugh I was so focused on the logEvent and logTime functions that I forgot to look at the bottom where they’re called…

1 Like