There is a piece of code

var someWords = ["clear", "business", "entertainment"]; function pickWord(someWords) { return someWords[Math.floor(Math.random() * someWords.length)]; } 

Interpreter issues

cannot read property length of undefined

But what about undefined if I even renamed the name of the argument on an already declared variable ??

  • four
    I bet you call the function like this: pickWord() - Grundy
  • So it was, but why then does the interpreter give an error on the wrong line where there is a problem? - Alex Stelmakh
  • It works, because in any function, you can pass any number of arguments - Grundy
  • Everything works, thanks for the clarification. - Alex Stelmakh

2 answers 2

in this case, the name of the parameter coincides with the name of the global variable and overlaps it inside the function.

Not to be confused with this, you can rename the parameter and get the following

 var someWords = ["clear", "business", "entertainment"]; function pickWord(words) { return words[Math.floor(Math.random() * words.length)]; } 

Thus, the value of the someWords parameter is determined by which parameter the pickWord function was called pickWord .


If the function was called without parameters: pickWord() then the value of all declared parameters of the function will be undefined .


To solve, you must either pass a global variable to the function

 var someWords = ["clear", "business", "entertainment"]; function pickWord(words) { return words[Math.floor(Math.random() * words.length)]; } pickWord(someWords); 

Or remove the parameter

 var someWords = ["clear", "business", "entertainment"]; function pickWord() { return someWords[Math.floor(Math.random() * someWords.length)]; } pickWord(); 

In this case, the global variable will be used.

    You do not finish speaking something. Everything is working

     var someWords = ["clear", "business", "entertainment"]; function pickWord(someWords) { return someWords[Math.floor(Math.random() * someWords.length)]; } var word = pickWord(someWords); console.log(word); 

    • and here so pickWord() will not work - Grundy
    • It works, yes. I called the function without agrument. But it is not clear why the interpreter gives an error, not where there is a problem, but on another line? - Alex Stelmakh
    • Damn, I'm just blind. All right, he gives. - Alex Stelmakh