0
Uncaught ReferenceError: lastn is not defined
    at verify (index.js:63)
    at HTMLButtonElement.onclick (index.html:12)

I wanted to know why I get an "undefined" error on the console? I am sure the variable has been defined . Take a look at my code. https://codepen.io/darkofdays/pen/WNpWPoB?editors=1010

  • 1
    Add the piece of code which contains the error to your question that's will be better – JS_INF Jun 21 '21 at 07:21
  • Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Jun 21 '21 at 07:22
  • Look again. You're defining lastn inside a function and then trying to access it outside that function – Kinglish Jun 21 '21 at 07:22
  • Problems are with the scope of your variables. Check again you are trying to access variables outside the functions that they are declared in. It wont work unless you either make them global or make those functions return them and use them as values for other variables where you are using them. – Beshambher Chaukhwan Jun 21 '21 at 07:24

1 Answers1

2

You variable is indeed defined, but not in the current scope. Simply, return the variable values from the functions in the verify function:

// verify
function verify() {
  function stringv() {
    let name = window.prompt('please enter your name:');
    if (name === null || name === "") {
      alert('please enter your name!')
      stringv();
    } else if (!/^[a-zA-Z]+$/.test(name)) {
      alert("your entered name isn't allowed!")
      stringv();
    } else {}
    return name
  }

  function stringln() {
    let lastn = window.prompt('please enter your lastname');
    if (lastn === null || lastn === "") {
      alert('please enter your lastn!')
      stringln();
    } else if (!/^[a-zA-Z]+$/.test(lastn)) {
      alert("your entered lastname isn't allowed")
      stringln();
    } else {}
    return lastn
  }

  function agev() {
    let age = "invalid"
    let errorMessage = ""
    while (!(age > 0)) {
      age = window.prompt(errorMessage + 'Enter ur Age');
      errorMessage = "'"
      ' + age + '
      " isn't a number"
    }
    return age
  }

  // Function calling
  let name = stringv();
  let lastn = stringln();
  let age = agev();

  // console.log 
  let output;
  output = 'Hello ' + name + ' ' + lastn + ' ' + age + '-years-old';
  console.log(output)
}
<button onclick="verify()">Enter Your name:</button>
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474