Search code examples
javascriptevalevaluate

Javascript eval() function not working properly


I'm currently making a calculator with HTML, CSS and Javascript, for practice. I found out that the "built in" eval function did the math from a string. But it doesn't work properly.

I don't know what the problem is. But when i for example do: 11+11/2 which should be 11. Becomes 16.5 for some reason. I have no idea why. I would really appreciate some help.

Here is the code:

    function revealAnswer(){
            var math = document.getElementById("numbersInputted");
            math.innerHTML += " = " + eval(math.innerHTML);

    }

Solution

  • 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.