0

I have recently started learning JS and while making my first project a problem occurred. Console shows that the variable billAm is not defined. I'm not sure why this is the case as I have already defined the variable?

Code snippet below:

function calculateTip() {
  let billAm = document.getElementById("billam").value;
  let serviceQual = document.getElementById("quality").value;
}

if (billAm === "" || serviceQual == 0) {
  alert("Please enter values");
}

let total = (billAm * serviceQual);
total = Math.round(total * 100) / 100;
total = total.toFixed(2);
document.getElementById("total").style.display = "block";
document.getElementById("tip").innerHTML = total;



document.getElementById("total").style.display = "none";

document.getElementById("calculate").onclick = function() {
  calculateTip();

};
<div id="background">
  <h3 class="headline">
    Tip calculator
  </h3>
  <input type=text id="billam" placeholder="Amount">
  <h3 class="review">
    How was your service?
  </h3>
  <select id="quality">
    <option disabled selected value="0">How was Your Experience?</option>
    <option value="0.3">30&#37; &#45; Outstanding</option>
    <option value="0.2">20&#37; &#45; Good</option>
    <option value="0.15">15&#37; &#45; It was OK</option>
    <option value="0.1">10&#37; &#45; Bad</option>
    <option value="0.05">5&#37; &#45; Terrible</option>
  </select>
  <button type="button" id="calculate">Calculate!</button>
  <div id="total">
    <sup>€</sup><span id="tip">0.00</span>
    <script src="script.js"></script>
  </div>
</div>
mshell_lauren
  • 5,171
  • 4
  • 28
  • 36
  • 2
    you are closing your function right after `let serviceQual=document.getElementById("quality").value;` and since `let` variables are scoped, `let billAm` doesn't exist outside the function – Calvin Nunes Jan 23 '20 at 12:50
  • 2
    Your `calculateTip()` function ends after the second `let` statement. The rest of the code is outside that function, so the variables are not declared in that scope. – Pointy Jan 23 '20 at 12:50

1 Answers1

2

Because you have defined it inside a function so it's scope is limited to that function.

You can refer this answer for more details https://stackoverflow.com/a/500459/1588446

Nitesh Phadatare
  • 315
  • 1
  • 2
  • 12