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 trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

Raquel Smith
Raquel Smith
10,683 Points

Why is there another function inside the if loop?

Why does Dave create a getStudentReport function outside the if statement to hold the student data when he could just put that code inside the if loop itself?

3 Answers

Karolin Rafalski
Karolin Rafalski
11,368 Points

There is a bit more going on behind the scenes. I am not sure if you want to jump down this rabbit hole at this time, but in case you do...

You don't want to put function declarations inside a conditional because you can't be certain of how it will be handled. (see second link for a detailed explanation).

As you progress in your studies, the information in the following links will be covered, so you don't have to worry if it doesn't make sense to you right away. But, I had found myself asking the same questions though and I found the following links helpful, even if they took a while to digest.

The difference between a function expression and a function declaration: http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip

Hoisting and scope: https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

Seth Kroger
Seth Kroger
56,413 Points

Many times when you have a long piece of code, it's best practice to break it up into smaller functions. It makes the code easier to read and understand. getStudentRecord() gives you, or anyone else reading the code, a quicker understanding of what's happening than trying to figure out what multiple concatenation statements are doing. It also makes the code more reusable. You can reuse getStudentRecord whenever you want to turn a student record into HTML without rewritting what you've written in the search function.

Raquel Smith
Raquel Smith
10,683 Points

Ok, I was just confused because the program we made was so short and we weren't going to reuse anything. So is it just to get in the habit of using functions so that your code is reusable?