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 trialLance Crow
8,037 PointsTwo different lines that define the variable "listItem"?
By the end of the video, this section of code starts with:
//New Task List Item
var createNewTaskElement = function(taskString) {
//Create List Item
var listItem = document.createElement("li");
So the variable listItem is defined with the .createElement method in the last line above, and listItem is also contained within the function createNewTaskElement.
Several lines later, the code asks the browser to:
return listItem;
Okay, so far, so good. But then, under the Add New Task section...
//ADD NEW TASK
var addTask = function() {
console.log("Add task...");
//Create a new list item with the text from #new-task:
var listItem = createNewTaskElement("Some New Task");
I am confused because we have now 1) redefined listItem, and 2) redefined it as calling the function that contained it in the first place!
I don't understand why you would redefine the listItem variable at all, instead of creating a NEW variable here with a NEW name. And I don't understand why you would write code that seems like it would loop back on itself like that. I know I'm a beginner here, but this feels something like...
var car = function(transportation) {
var steeringWheel = document.createElement("steering")
}
var steeringWheel = car("Some New Transportation");
The steeringWheel is inside the car. So how can you later say that same car IS the steeringWheel?
Am I making sense here? Am I looking at this all wrong? Am I missing something? Can anyone help me out?
Thanks, Lance
2 Answers
Grant Lacey
6,103 PointsIf i recall the code you're showing are excerpts not the complete document. I think they (var = listitem) may be local variables that are only used within the scope of the method, therefore unrelated to one another. I believe the intent was to make the code more readable and maintainable by others or yourself at a later date. Having sensical variable names in functions can make them easier to understand.
**just my stab at it. By no means an authoritative answer.
Lance Crow
8,037 PointsYes, I did forget about variables in different scopes. And I realize the code isn't really "finished" yet. Still, as a beginner, that's a really confusing practice to me - different variables with the identical names.
Thanks for your help, Grant.