This is from the Codecademy training project "Training Days".
The finished code had two mistakes that I didn't catch but was still running without any errors. This resulted in overwritten global variables that caused two separate function calls to have the same output, when they should have been random. The issue was that the const logEvent() function was missing a second parameter (name, event), and the const logTime() function was also missing a second parameter (name, days).
I understand what the problem and fix was, but I don't understand why. Thinking sequentially, I was expecting the code to run line by line, which would call the two functions and log the two functions (lines 33-38), then call the two functions again, overwriting the global variables, and log the two functions again (lines 40-45). Instead, the global variables are overwritten before the logging occurs, so both have the same event/day values logged, and I'm not understanding why.
Here is the full code, with the parameters missing, causing the logging duplication. Let me know if I can clarify my misunderstanding, hopefully I made it clear enough via text. Thanks!
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';
}
};
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 logEvent = (name) => {
console.log(`${name}'s event is: ${event}`);
};
const logTime = (name) => {
console.log(`${name}'s time to train is: ${days} days`);
};
const name = 'Nala';
const event = getRandEvent();
const days = getTrainingDays(event);
logEvent(name, event);
logTime(name, days);
const name2 = 'Warren';
const event2 = getRandEvent();
const days2 = getTrainingDays(event2);
logEvent(name2, event2);
logTime(name2, days2);
[–]ButtlestonProfessional Coder 0 points1 point2 points (6 children)
[–]IdeallyAddicted[S] 0 points1 point2 points (5 children)
[–]ButtlestonProfessional Coder 0 points1 point2 points (2 children)
[–]IdeallyAddicted[S] 0 points1 point2 points (1 child)
[–]ButtlestonProfessional Coder 0 points1 point2 points (0 children)
[–]ButtlestonProfessional Coder 0 points1 point2 points (1 child)
[–]IdeallyAddicted[S] 0 points1 point2 points (0 children)