Search code examples
javascriptstringdynamic-typing

.value return string until I save it to variable


I have case that I'm not sure how to explain: What bugs me is, I open the code, I write some values (example: How much was you bill: 100 How was your service: 10 How many people are sharing: 2) and before I click Calculate I open the console. If I write:

>bill.value
<"100"

I get a string, as expected. But then I click Calculate and what I get is:

100
5

Why 100?? Why does it suddenly return number insted of string?

How can I do math with it at the end. Only thing I'm turning into a number is Number(bill.value). Service and people should still be strings?

var button = document.querySelector("button");

var tip = document.getElementById("tip");

var total;


button.addEventListener("click", function() {

  var bill = document.querySelector("input");

  console.log(bill.value)

  var people = document.getElementById("people").value;

  var service = document.getElementsByTagName("select")[0].value;

  total = (service * Number(bill.value)) / people
  tip.textContent = total;
  console.log(total)
});
<h1>Tip Calculator</h1>

<div>How much was your bill?</div>

<label for="bill">$</label>
<input type="number" id="bill">



<div>How was your service?</div>

<select>
  <option disabled selected value="0">Choose</option>

  <option value="0.30">30% - Outstanding</option>
  <option value="0.20">20% - Good</option>
  <option value="0.15">15% - It was okaya</option>
  <option value="0.10">10% - Bad</option>
  <option value="0.05">5% - Terible</option>
</select>

<div>How many people are sharing the bill?</div>
<label>
  <input type="number" id="people">people</label>

<button>Calculate!</button>

<span id="tip"></span>


Solution

  • Edit: Now understanding you're asking about implicit conversion's I've updated my answer.

    Take a look at the code below, you'll notice that product holds a value that is a number while sum holds a string. An expression containing two strings separated by a + operator will always result in the concatenation of the strings (What most expect).

    On the other hand the * operator is not valid for two strings so it attempts to convert the strings into values that do support the * operator, namely numbers. If both strings are valid integers or floating point numbers the result is the product of the two numbers. If not, the result will be NaN.

    var a = '2.0';
    var b = '3.0';
    
    var sum = a + b;
    var product = a * b;
    
    console.log(product); // 6.0
    console.log(sum); // "2.03.0"