Eval, Why does it do what it does?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tcommander
    New Member
    • Feb 2008
    • 2

    Eval, Why does it do what it does?

    Okay, recently for class, we ran into the following problem:

    When we entered in
    var x=1
    eval(x + "2*2")
    and had it returned and printed to the screen, we came out with 24 as the result. This defies all logic that we can think of, and so we decided to ask for help. When each section is done individually within the eval function, we get x is the value of 1, 2*2 is the value of 4, but when they are added, it always comes out as 24. Anybody out there know why?
  • rnd me
    Recognized Expert Contributor
    • Jun 2007
    • 427

    #2
    Originally posted by tcommander
    Okay, recently for class, we ran into the following problem:

    When we entered in
    var x=1
    eval(x + "2*2")
    and had it returned and printed to the screen, we came out with 24 as the result. This defies all logic that we can think of, and so we decided to ask for help. When each section is done individually within the eval function, we get x is the value of 1, 2*2 is the value of 4, but when they are added, it always comes out as 24. Anybody out there know why?
    sure, 12 * 2 = 24.

    what's not to understand?

    seriously though, here is the explination.

    you are adding a number to a string.
    remembering back to math class: PEMDAS, or parenthesis go first.
    thus, it will add the number x to the string, and then evaluate the combined expression.

    the "+" operator will only perform a mathematical addition if both sides are numbers. if one or both sides are strings, it is not an addition operator, it is a string concat operator,

    so what you are doing is
    1: 1+"2*2" // = "12*2"
    2. eval ( "12*2" ) // = 24


    does that help?

    Comment

    • tcommander
      New Member
      • Feb 2008
      • 2

      #3
      Originally posted by rnd me
      sure, 12 * 2 = 24.

      what's not to understand?

      seriously though, here is the explination.

      you are adding a number to a string.
      remembering back to math class: PEMDAS, or parenthesis go first.
      thus, it will add the number x to the string, and then evaluate the combined expression.

      the "+" operator will only perform a mathematical addition if both sides are numbers. if one or both sides are strings, it is not an addition operator, it is a string concat operator,

      so what you are doing is
      1: 1+"2*2" // = "12*2"
      2. eval ( "12*2" ) // = 24


      does that help?
      Yes, thank you so much. That makes complete sense

      Comment

      • traineeirishprogrammer
        New Member
        • Jul 2007
        • 24

        #4
        you should not need to use eval ever anyway. there are easier ways to covert type string to number

        Comment

        Working...