-2

view my code

enter image description here

This code doesn't work if I put variable x outside the function like this. In this case, it wouldn't alert my input value, but the initial value which is null in this case. The error is fixed if I put x inside the function. Does anyone know why?

Thanks so much!

Rakesh kumar Oad
  • 1,332
  • 1
  • 15
  • 24
Tanh
  • 229
  • 1
  • 3
  • 6
  • 1
    where is the code buddy? – Bharat Jul 28 '21 at 04:17
  • 1
    Please no images of code. – no ai please Jul 28 '21 at 04:17
  • 2
    And you really shouldn't be using w3schools.com. Their content is awfully out of date! – no ai please Jul 28 '21 at 04:18
  • 1
    var would work without error even if it's inside or outside. can you tell what is the error? – Bharat Jul 28 '21 at 04:20
  • 1
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+input+value+empty+when+variable+outside+function) of [Can't retrieve value from input form outside function](/q/46155059/4642212). – Sebastian Simon Jul 28 '21 at 04:21
  • 1
    Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Jul 28 '21 at 04:22
  • 1
    And the reason it does not work is the line is executed when the page is getting loaded. But when you click on button, it will simply show last value from x – Bharat Jul 28 '21 at 04:22

1 Answers1

1

You're reading the value before the user enters it.

Here's your program:

  1. x is "".
  2. User clicks something
  3. Alert x (which is "").
  4. Basically alert("").

If you place it in the function, the value is read as soon as the user clicks something. Because they're both part of the same synchronous operation, there's no delay.

But if your function is asynchronous, there's a problem. The user can change it in the background.

So read it when it is being clicked.

no ai please
  • 732
  • 3
  • 11
  • 24