Bummer! You must be logged in to access this page.

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

Regarding Variable Scope

In the following code the variable listItem is created within a function. I was under the impression that variables created within functions are local to that function (as long as it uses the var keyword).

However, the listItem variable is used again in the second addTask function.

How is the second function able to use this variable if it is local not global? Is it because of return listItem?

  var createNewTaskElement = function ('taskString') {
  var listItem = document.createElement('li'); 
  var checkBox = document.createElement('input');
  var label = document.createElement('label');
  var editInput = document.createElement('input');
  var editButton = document.createElement('button');
  var deleteButton = document.createElement('button');

  listItem.appendChild(checkBox);
  listItem.appendChild(label);
  listItem.appendChild(editInput);
  listItem.appendChild(editButton);
  listItem.appendChild(deleteButton);

  return listItem;
}

//Add a new task
var addTask = function() {
  console.log("Add task...");

  var listItem = createNewTaskElement('Some text');
  incompleteTasksHolder.append(listItem);
}

2 Answers

Both are local variables.

At the end of the 'createNewTaskElement' function, you are returning 'listItem' which is pulling all the elements of a list item and appending it to the 'listItem' variable. Then it is returned.

However, you're still creating a new variable named 'listItem' in the 'addTask' function.

In 'addTask' you're calling the 'createNewTaskElement' and assigning it to a local variable called 'listItem'.

Each variable could be named something different and it would still work.

The second function is declaring its own listItem variable within it's scope. Both variables are contained within the scope of those functions and will not interfere with each other.