0

The console throws: index.js:5 Uncaught TypeError: Cannot read property 'length' of undefined at checkUserName. Could it have something to do with the scope?

It's worth mentioning the code works fine when I replace the condition in my if statement by: inputEl.value.length

const inputEl = document.querySelector("input");

function checkUserName(num) {
  var elMsg = document.querySelector("h1");
  if(this.value.length <  num) {
    elMsg.textContent = "name must be at least 5 letters long";
  } else {
    elMsg.textContent = "word's long enough";
  }
}

inputEl.addEventListener("blur", function(){
  checkUserName(5)
}, false)
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Practise App</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
  <input type="text" name="ronal" value="">
  <h1></h1>
    <script src="index.js" type="text/javascript"></script>
  </body>
</html>
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • 1
    This has nothing to do with named functions or anonymous functions. The `this` value is determined by how the function is called, and the two functions are called differently. – Quentin Feb 03 '21 at 11:08
  • 1
    "*lives inside an anonymous function*" - it doesn't. A function has no "home", it just *is*. What you refer to is that it is *called* from an anonymous, but that doesn't matter. It's always about *how* it is called, no matter from where. You're looking for `checkUserName.call(inputEl, 5)`, or `checkUserName.call(this, 5)` inside the event handler. – Bergi Feb 03 '21 at 11:09
  • 1
    @Bergi I believe it would be `checkUserName.bind(this, 5)`, otherwise the function would be called immediately – Jeremy Thille Feb 03 '21 at 11:15
  • 1
    @JeremyThille I wrote *inside* the event handler, not *as* the event handler. To replace the `checkUserName(5)` call that the OP currently has. – Bergi Feb 03 '21 at 11:18
  • 1
    Allow me to disagree, type this in your console : `const handlerFunc= () => console.log("Handler!"); setTimeout( handlerFunc.call(this), 3000);` The handler is being executed immediately. If you use `.bind()` it will indeed be called after 3000ms. – Jeremy Thille Feb 03 '21 at 11:25

0 Answers0