Results 1 to 3 of 3

Thread: [RESOLVED] Help da jsnoob pls =)

  1. #1
    Join Date
    Oct 2009

    resolved [RESOLVED] Help da jsnoob pls =)

    ok so I finished hltmgoodies primer and w3schools tutorial on javascript and I'm getting better with looking at a script to figure out what they do but I wanted to work some exercises I had to build from scratch to help it all sink in. I finished my first exercise which was...

    (Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Javascript.)

    Then I modified it alittle so that if nb=nc a new alert would pop. So I proceeded to change my ELSE to an IF and added the 3rd IF condition. Being a leet jsnoob that I am the below script looks like it should work just fine, and I suppose it does when the variables are equal but if they arn't then you get two pops, either the <alert or >alert then the =alert. I don't understand why the =alert pops when it shouldn't....

    <title>My first forum Post YAY</title>
    <script type="text/javascript">

    function max()
    var nb=prompt("Enter any random number..","");
    var nc=prompt("Enter another random number...","");

    if (nb>nc)
    alert(nb+ " is the highest number YAY");
    if (nb<nc)
    alert(nc+ " is the highest number YAY");
    if (nb=nc)
    alert("wtf why is this alert popping up when nb and nc are not equal? sigh");

    <body onLoad="max()">


    Playing around with the code I eventually got it to work by removing the strings

    + " is the highest number YAY"

    so that it just reads alert(nb) and alert(nc)

    But I am really curious to know why I had to do this? Thanks in advance

  2. #2
    Join Date
    Oct 2008
    if (nb=nc)
    See the problem yet? When you use single equal you do assignment of value and therefore it is always true that nb equals nc there as you have assigned nc's value to nb, so the body of the if statement is executed. You intend to use double or even triple equal to do comparison there: if (nb == nc) ........

  3. #3
    Join Date
    Oct 2009
    eek I want the last hour of my life back!! oh well, least I probally won't forget that lesson... thx

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center