Home > other >  Why this 'rad' variable only work inside this pol.addEventListener but when i put its outs
Why this 'rad' variable only work inside this pol.addEventListener but when i put its outs

Time:10-11

When i put this 'rad' variable in addEventListener the whole code work but as soon as i put this out of function it says that its equal 0. Is it out of scope? Cause i don't want to duplicate this variable in both functions

let promien = document.querySelector("#r");
const pol = document.querySelector(".pol");
const obj = document.querySelector(".obj");

const rad = Number(promien.value);
pol.addEventListener("dblclick", function () {
  alert(
    `The total area is equal ${Math.floor(4 * Math.PI * Math.pow(rad, 2))}`
  );
});

obj.addEventListener("mousedown", function () {
  const rad = Number(promien.value);
  alert(`The volume is equal ${Math.floor((3 / 4) * Math.PI * rad)}`);
});

HTML:

    <label for="">Promien</label> <input type="number" id="r" /> <br />
    <button >Calculate area</button>
    <button >Calculate volume</button>

    <script src="app.js"></script>
 

CodePudding user response:

This has nothing to do with the variable or where it's located. The problem is that you're trying to read a value which doesn't exist yet.

When the page first loads, you do this:

const rad = Number(promien.value);

The page just loaded. The user hasn't typed anything yet. promien.value doesn't contain anything yet.

Basically, you can't capture a value or perform math on input that the user hasn't yet provided. You can wait until the user provides that input, by performing this operation in an event handler. Exactly like you do here:

obj.addEventListener("mousedown", function () {
  const rad = Number(promien.value);
  alert(`The volume is equal ${Math.floor((3 / 4) * Math.PI * rad)}`);
});

i don't want to duplicate this variable in both functions

There's exactly zero harm in declaring a variable in both functions. But if you want you can declare a single variable in global scope and use it within the functions. For example:

let rad = 0;

pol.addEventListener("dblclick", function () {
  rad = Number(promien.value);
  alert(`The total area is equal ${Math.floor(4 * Math.PI * Math.pow(rad, 2))}`);
});

obj.addEventListener("mousedown", function () {
  rad = Number(promien.value);
  alert(`The volume is equal ${Math.floor((3 / 4) * Math.PI * rad)}`);
});
  • Related