There are a whole bunch of reasons why this is the wrong approach.
First, innerHTML
returns a string containing, not only the text content of an element, but also any nested HTML elements as well. If it’s just the text you want, use textContent
.
Next, by having the user input the actual math operator they want to use in the same string with the numbers creates more confusion. Have the user enter that separately and then you can use if/then
logic to ultimately use the correct operator.
Next (and this is the important part), don’t ever use eval()
. It is not required to solve just about any problem you could encounter, but it opens up the door to “Cross Site Scripting” attacks on your website. Additionally, it manipulates the this
binding and executes its code in its own scope.
What you really need to do is simply convert the string input into a number so that you can do math with it. You can do this with parseInt()
and parseFloat()
So, your line could be:
math.innerHTML += " = " + parseFloat(math.textContent);
Lastly, for math, the order of operations is:
- Parenthesis
- Exponents
- Multiplication
- Division
- Addtion
- Subtraction
You can see that division is done prior to addition and that means that in your expression: 11 + 11/2
, first 11/2
is evaluated (5.5) and then it is added to 11
(16.5).
Finally, remember that the +
operator in JavaScript can mean mathematical addition or string concatenation and if one of the operands is a string, the other will be converted to a string.
1
solved Javascript eval() function not working properly [closed]