Search code examples
javascriptfunctionparametersscopechaining

Javascript: Flexibility of function parameters?


The description of Javascript function parameters on W3Schools wasn't very clear, so I just want to clarify.

From my understanding, there isn't a type restriction; the "real value" of the parameters are passed into the method. Is there a way to pass objects or elements? Or is that what is meant by "real value"?

For example:

The function displayText meant to take input text and set a display to show a new word in the given input text, going to the next word every time it's called.

function displayText() {
    var text = document.getElementById("words").value; 
// Since text is initialized   
// every time the method is called, 
// it will always start at the beginning of the text area. 
// Not sure how to fix this since making `text` 
// a global variable doesn't work 
    var list = text.split(/[ \t\n]+/);
    displayNext(list, "display");
}

There is a "helper" method, displayNext, which is supposed to shift to the next word in the list and sets the display to that word.

function displayNext(list, textboxID) {
    document.getElementById(textboxID).innerHTML = list.shift();
}

This isn't working as it is intended. I'm fairly sure it's because I've mucked up something with the parameters, since displayNext sets innerHTML to null. list must have not passed properly. I'm not sure how to fix this.

I'm sure there's a more efficient way to do this, but this is a good opportunity to learn how Javascript parameters actually work, so I thought I'd ask.

JSFiddle


Solution

  • Based on the comments in your code, it sounds like you want displayText() to display the "next" word each time. To do that, you have to create some place to store some state about which word is the next one to display. As you have it now, you create a new array every time and always display the first word.

    The simplest way is to create a variable outside your function in some lasting scope where you store the word number:

    var wordNum = 0;
    function displayText() {
        var text = document.getElementById("words").value; 
        var list = text.split(/\s+/);
        if (list.length !== 0) {
            // make sure we aren't off the end of the list
            wordNum = wordNum % list.length;
            displayNext(list[wordNum++], "display");
        }
    }
    
    function displayNext(text, textboxID) {
        document.getElementById(textboxID).innerHTML = text;
    }
    

    For a lot more info about arguments to Javascript functions and even how you can detect what arguments were passed or overload arguments, see this answer: How to overload functions in javascript? and for more info about how arguments are passed: Javascript by reference vs. by value