Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialLuqman Shah
3,016 PointsConfused with quiz question code
"After the code below runs, what value is stored in the variable dayOfWeek:"
function getDay() {
return "Monday";
alert("Calculating day");
return "Friday";
}
var dayOfWeek = getDay();
So I was given this question in the quiz, according to the video, I thought that "the return statement should be the last thing in a function." So from this statement, I assumed that the the last return statement in the code block would run, instead of the first one, thus giving a return value of Friday. Can someone please explain to me where and why I messed up?
Also, I'm a little confused to why this given code was written like this, shouldn't it be written like this, according to my understanding, when working with return statements:
function getDay() {
return "Monday";
return "Friday";
}
alert(getDay);
// or
var dayOfWeek = alert(getDay);
Why is there an alert dialog within the code block, when we could've just made the return value run in an alert dialog. Wasn't that a key takeaway from the lesson?
2 Answers
Steven Parker
231,269 PointsSome functions perform a task but don't return anything. But if the purpose of the function is to return a value, then there should be a "return" at the end of the function. But it doesn't have to be the only one in the function. And like any statement, it is executed when it is encountered.
What's special about the "return" statement is that when one is encountered, execution in the function stops and resumes where the function was called. The point of this quiz question is to confirm your understanding of this.
The example serves the purpose of testing your knowledge but it should not be considered a model of good code.
Rares Conea
Courses Plus Student 15,000 PointsHi Luqman,
The code in your function runs till the first return statement, all the code written after will not be reached. For your second question, you can not store an alert inside a variable, alert is used to display an error, let s say, on the screen. You can use prompt() to store the info you write in the browser in a variable.