Q:

reusable javascript function not taking the variable

I am trying to learn javascript and write a reusable function. I followed a tutorial and of course you can pass either a variable, or the exact data type- and I am trying to change the color of <div id="age">. The changeColor function worked, when displayE1 was called explicitly inside the function. I want to be able to change the color of anything, and passing displayE1, 'age', and 'displayE1' didn't work.
   <div id="age"></div>
    <button onclick="changeColor('blue', displayE1);" >blue</button>
    <button onclick="changeColor('red', age)">red</button>

    <script type="application/javascript">
        var age = "age"
        function grabAge() {
            var result = prompt('how old?', '');
            var displayE1 = document.getElementById("age");
            displayE1.innerHTML = result

            function changeColor(newColor, idReference) {
                idReference.style.color = newColor;
            }
        }
        grabAge()
    </script>

This worked
function changeColor(newColor) {
    displayE1.style.color = newColor;
}

Why isn't this function reusable?

A:

It is not reusable because the function is NOT defined in window scope as you are calling it. It is a local method to the grabAge method. Also displayE1 is also not in global scope.
For your code to work, it would need to look line this
var age = "age", displayE1;
function grabAge() {
    var result = prompt('how old?', '');
    displayE1 = document.getElementById("age");
    displayE1.innerHTML = result
}

function changeColor(newColor, idReference) {
    idReference.style.color = newColor;
}

grabAge();

Notice how changeColor is not inside the other method and displayE1 is defined outside the function.

