0
Declaring variables outside the EventListener
Hello everyone! I am writing a javascript code, which will solve quadratic equations. However, there is a problem. It should be about the visibility, but I am not sure. let a = document.querySelector('#a'); let b = document.querySelector('#b'); let c = document.querySelector('#c'); let button = document.querySelector('#button'); button.addEventListener('click', function() { let D = (Math.pow(Number(b.value),2) - (4 * (Number(a.value)) * (Number(c.value)))); console.log(D); }); This code finds the discriminant and works properly. But when I declare D outside the EventListener, it doesn`t work. What is the problem, and how can I declare D outside the EL, so it will work? Thanks in advance!
3 Antworten
+ 1
Change let to var.
That's because any variable created with let can only work inside the function.
But var creates a global variable which can be used anywhere.
It should be var D=...
And not let D=...
+ 1
Why you want variable <D> outside the event handler though? can you tell me?
0
// make calculation outside of function and use function just to output it.
let a = document.querySelector('#a');
let b = document.querySelector('#b');
let c = document.querySelector('#c');
let button = document.querySelector('#button');
let d = (Math.pow(Number(b.value),2) - (4 * (Number(a.value)) * (Number(c.value))));
button.addEventListener('click', function() {
console.log(d);
});