JavaScript DOM Scripting By Example Improving the Application Code Refactor 1: Create List Items

Label outside the scope

Hi, I don't understand this part. Why do we have to return it in the function to work ?

In the video: "with appendToLI, I can't append the checkbox to it. Well that's because the label is being created outside the scope beyond the checkbox's reach. So if appendToLI returned the label once it was finished, you could call appendChild on it and pass in the checkbox."

1 Answer

Steven Parker
Steven Parker
195,705 Points

Normally, any variables created in a function go out of scope and are disposed the moment the function ends. However, any value that is returned by the function is available to the caller.

Begana Choi
Begana Choi
Full Stack JavaScript Techdegree Student 9,022 Points

still cannot understand clearly. can you explain more simply? sorry, maybe I'm too beginner to understand it. so if I understand it, if we want to call checkbox function through (into) the label function, we need to return label function first? it just mixed up in my head... please help me to understand it.

Steven Parker
Steven Parker
195,705 Points

Perhaps a code example would help:

function scopeTest() {
    var first = "one";
    var last = "two";
    return first;
}

var first = scopeTest();
console.log(first);  // this will output "one"
console.log(last);   // this will cause a ReferenceError, since last is not defined here