ternary statement or conditional operator - Beginner question

Discussion in 'JavaScript' started by askscript, Nov 6, 2008.

  1. #1
    This one works well"

    Now if i assign the alert value to a var value:

    If i did the above the 2 alerts will appear one after another regardless of what number i key in the prompt. Why is that?
     
    askscript, Nov 6, 2008 IP
  2. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Cause you try to assign the alert() executions to variables, which is not possible. When the parser reaches to the alert() it executes it and continues.. To make the second code work you can use eval(); Change the code to:
    <script language="javascript" type="text/javascript">
    <!--
    var temp = prompt('Please enter the current temperature', '');
    var warm = "alert ('It's too warm, go get cool down')";
    var cool = "alert ('Go and warm yourself up')";
    
    temp > 100 ? eval(warm) : eval(cool) ;
    -->
    </script>
    Code (markup):
    This way you store the string, with the code you want executed later, in the variables warm and cool. eval() simply executes the code which is given to it, so your alerts will execute at the right place.. BTW, the first code you posted is way better than the second one, I don't know why you are trying to change it..
     
    xlcho, Nov 7, 2008 IP
  3. askscript

    askscript Member

    Messages:
    59
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    Thks for enlightening me. I am not changing the code. I got it from one of the exercise question and try to play around with it. I am just a self-taught learner trying to figure out the whole javascript thing.
     
    askscript, Nov 7, 2008 IP
  4. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I'm also self-taught, but I got pretty far. Don't hesitate asking whatever you can't understand. Wish you luck and success :)
     
    xlcho, Nov 7, 2008 IP
  5. askscript

    askscript Member

    Messages:
    59
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #5
    Thank you very much, I will. :)
     
    askscript, Nov 7, 2008 IP
  6. askscript

    askscript Member

    Messages:
    59
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #6
    you are right. The alert is still superior than the eval. However, now i know that we cannot assign alert to any var value.
     
    askscript, Nov 7, 2008 IP
  7. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #7
    just rethink it:

    var temp = prompt('Please enter the current temperature', '');
    
    alert (temp > 100 ? 'It\'s too warm, go get cool down' : 'Go and warm yourself up')
    PHP:
     
    MMJ, Nov 8, 2008 IP