Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    New Coder
    Join Date
    Dec 2013
    Posts
    17
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Issues with logical operators

    Hello there,

    I am trying to create a straight forward string of loops that start prompts and alerts.

    I believe my issue lies between the else if and the else.

    If I type in 5 it will give me the prompt for both the else if and the else, I would like it to only be for the else if.

    If I type 6 into the initial prompt it will give me both prompts from the else if and the else also. As 6 is the value that is to be applied in the else, I don't know why I am also getting the else if prompt.

    You maybe wondering why the else and the else if are prompts instead of alerts. It is my intention to make this loop back and ask the initial question again. I was going to start by copying the initial prompt and variables and placing them in each optional loop, but if there is a way or command to make the script go back to the top I think that would be ideal.

    Please let me know if additional information is needed, any assistance is appreciated.

    Code:
    var value = 4
    var answer = prompt ("What is 2+2?", "");
    
    if (answer == 4)
    	{alert ("Well Done sir, you can add!")
    		
    		}
    else if ( answer = 3 || 5)
    		{prompt ("Well your close but wrong is wrong, Try again")
            	
    			}
    			
    else( answer >= 6 || answer <= 2)
    		{prompt ("Your wayoff, go again?")
    			
    			}
    			
            //print (answer)}

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,373
    Thanks
    11
    Thanked 592 Times in 572 Posts
    use more braces to not only fix your problem, but to make you problem visually apparent as well.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #3
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,301
    Thanks
    23
    Thanked 612 Times in 611 Posts
    Code:
    <script type="text/javascript">
    var value = 4;   // YOU NEVER USE THIS SO WHY HAVE IT?
    var answer = prompt ("What is 2+2?", "");
    
    if (answer == 4){
    	alert ("Well Done sir, you can add!");
    }else if ( answer == 3 || answer == 5){         // YOU HAVE '=' IT ASSIGNS, NOT '==' TO COMPARE
    	prompt ("Well your close but wrong is wrong, Try again")
    }else if(answer >= 6 || answer <= 2){  // YOU ARE MISSING THE IF HERE
    	prompt ("Your wayoff, go again?");
    } // YOU DO NOTHING TO HAVE THE TWO ESLE IF'S CHECK THE ANSWER A SECOND TIME
    </script>
    Last edited by sunfighter; 12-31-2013 at 07:34 PM.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #4
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,301
    Thanks
    23
    Thanked 612 Times in 611 Posts
    Try this one:
    Code:
    <script type="text/javascript">
    var answer = prompt ("What is 2+2 ?", "");
    
    while (answer != 4){
    	if ( answer == 3 || answer == 5){
    		answer = prompt ("Well your close but wrong is wrong, Try again");
    	}else if(answer >= 6 || answer <= 2){
    		answer = prompt ("Your wayoff, go again?");
    	}
    }
    </script>
    It's good habit to indent and to place a ';' at the end of a line of code.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by sunfighter View Post
    Try this one:
    Code:
    <script type="text/javascript">
    var answer = prompt ("What is 2+2 ?", "");
    
    while (answer != 4){
    	if ( answer == 3 || answer == 5){
    		answer = prompt ("Well your close but wrong is wrong, Try again");
    	}else if(answer >= 6 || answer <= 2){
    		answer = prompt ("Your wayoff, go again?");
    	}
    }
    </script>
    It's good habit to indent and to place a ';' at the end of a line of code.

    There is a big difference between "your" (belonging to you) and "you're" (contraction of you are).
    And there is a big difference between knowing your s*h*i*t and knowing you're s*h*i*t!

    Another version which traps NaN:-

    Code:
    <script type = "text/javascript">
    
    var repeat = true;
    while (repeat) {
    var ans = parseFloat(prompt("What is 2 + 2?",""));
    if ((isNaN(ans)) || (ans == null) || (ans !=4)) {
    alert ("Wrong answer!  Try again!");
    }
    else {
    repeat = false;
    alert ("4 is the right answer");
    }
    }
    
    </script>
    Last edited by Philip M; 01-03-2014 at 08:38 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    You should be using === instead of == for the comparisons

    4 == '4' //true - converts the number to a string before comparing
    04 == '04' // false - after converting the strings don't match
    4 === '4' // false - a number isn't a string


    Also prompt() and alert() are now obsolete and shouldn't be used - they can be easily turned off in the browser so that your visitors will never see when you use antiquated calls like that.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by felgall View Post
    You should be using === instead of == for the comparisons
    I don't see how that can be in any way useful here. == will work just fine. Which user will answer '4'? And if he does, surely that answer is correct.

    There is no <== or >==, so === is of limited utility. Better to use Number() to convert the values to numbers (if necessary) at the outset before any comparisons are made.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    New Coder
    Join Date
    Dec 2013
    Posts
    17
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Thanks for the help.

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Philip M View Post
    I don't see how that can be in any way useful here. == will work just fine.
    Yes but it is better to get in the habit of never using == or != as there are many situations where they can cause problems and no situations where they are actually needed.

    Just because a bad command that should never have been part of the language in the first place doesn't do any harm in a particular situation doesn't mean that you should use it in place of the correct one.

    The == and != will work for beginner level JavaScript but often cause problems with intermediate level code and almost always create problems with advanced level code which is why it is recommended by anyone who actually knows JavaScript properly to NEVER use them. Feeding your code through JSLint will give an error on all == and != use.
    Last edited by felgall; 01-07-2014 at 08:33 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by felgall View Post
    The == and != will work for beginner level JavaScript but often cause problems with intermediate level code and almost always create problems with advanced level code which is why it is recommended by anyone who actually knows JavaScript properly to NEVER use them. Feeding your code through JSLint will give an error on all == and != use.
    Well, in the 15+ years I have been coding Javascript, I have never encountered any of the problems which you allude to. I use === only on the rare occasions when it is actually required.

    As I see it there is no reason to change == to === in a check like if (x == 'test') when you know it for a fact that x can only be a string.
    Last edited by Philip M; 01-07-2014 at 08:53 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #11
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,373
    Thanks
    11
    Thanked 592 Times in 572 Posts
    Quote Originally Posted by felgall View Post
    The == and != will work for beginner level JavaScript but often cause problems with intermediate level code and almost always create problems with advanced level code which is why it is recommended by anyone who actually knows JavaScript properly to NEVER use them. Feeding your code through JSLint will give an error on all == and != use.
    actually i find that for js beginners coming from c/java, != seems to cause more trouble than !==. i think it's because it's harder for strict-type mindsets to consider the automatic type conversion as they plan their program's flow. As they get better acquainted with js and loose-typing in general, they understand the difference between "x!=2" and "x!==2".

    === is typically faster than ==, so if you can use ===, do so, but don't be afraid to use == when apropos.

    Personally, i use them both about 50/50, depending on the need.

    • "x!=null" is especially handy for screening out null and undefined in one swoop.
    • " typeof x != 'boolean' " is faster on most computers than " typeof x !== 'boolean' " for some reason
    • "if(index==0)" works even if i set index to the string "0" from localStrorage , a cookie, a url segment, or felgall's favorite function: prompt() (j/k)



    if you embrace and understand the JS typecasting, (!=,==,!,etc) can often half the needed comparisons when validating data/input compared to using stricter operators.

    js lint does not find js mistakes in your code. it find things that LOOK like mistakes (to other humans) in your code. Often times, programmers think at a glance that "!=" means "!==", which to them it does. In that respect, code that uses the extra equal will be more readable to more programmers as it matches prior exceptions better. JSLint, like any other tool has is limitations that need to be understood to correctly use it. It's can't tell what you meant, so it complains to you so that, if indeed you did mean to use "!==" instead of "!=", you would spot the notice. JSLint was never meant to be some blind arbitrator of good and bad that should be dogmatically followed to the hilt; it's just a code readability tool that attempts to offers useful suggestions. As you get less mistake-prone in JS, feel free to relax more and more options like eval, == and !=, unfiltered for-in, etc... These tell JSLint that "i'm not making noob mistakes, this is good code, tell me about the other "mistakes" you can find that i DO care about."

    However, Doug Crockford has also severely chastised people for pretending that JS is like another language, x,y, or z. He says that they can get away with such nonsense for a deceivingly long time, but that coders are better off in the long run actually learning JS and writing JS that's meant to be JS.

    We are all hypocrites when put under the microscope.
    Last edited by rnd me; 01-07-2014 at 09:59 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    alert ("5" === 5); // false
    alert ("5" >=4); // true

    To me that says it all.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #13
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Philip M View Post
    alert ("5" === 5); // false
    alert ("5" >=4); // true

    To me that says it all.
    "5" is ASCII character 53 and 53 is greater than or equal to 4 so of course that's true. There are many ways of comparing when the types are different.

    Now if you were comparing "3" >= 4 then you are dependent entirely on which way the language decides to treat it - it ought to be true and false both at the same time as there are ways of interpreting it both ways. When using > or < you should always test first to make sure that both values are the same type first. That's one of the biggest PROBLEMS with weakly typed languages.

    At least JavaScript has === and !== so only the < and > comparisons need the extra test for type being the same first.


    alert(Number('5') >= 4) or alert('5'.charCodeAt(0) >= 4) // both true
    alert(Number('3') >= 4) or alert('3'.charCodeAt(0) >= 4) // one false and one true
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #14
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by felgall View Post
    "5" is ASCII character 53 and 53 is greater than or equal to 4 so of course that's true.
    That cannot be right.

    alert ("5433">=5432); // true
    alert ("5433">=5435); // false

    >= makes the type conversion to number. Just like ==.

    In my experience it is not common to wish to compare two variables of different types. If a form field value is a number it should be converted from a string value to a number by one of several different methods at the outset. If it is a string then == is still fine, indeed === is pointless if both variables are known to be of the same type.

    The answer is to know what you are doing, not slavishly follow inflexible rules peddled by gurus. Crockford is very knowledgeable, but he is not the Pope. As rnd me says, use the code most suited to the need. Once again, I use === only on the rare occasions when it is actually required.
    Last edited by Philip M; 01-08-2014 at 08:49 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #15
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    I didn't say that JavaScript doesn't convert the string to a number when you do that comparison - it just might not be what you want ot to do for the comparison. My point is that there are multiple ways of converting from one type to another and the one JavaScript chooses when you don't specify it directly may not be the one you want. When you let the language choose when to do conversions it will convert the way it wants even when that isn't what you intended.

    A simple example of this is a string/number comparison. In JavaScript the string will be converted to a number before they are compared. In PHP the number sill be converted to a string before they are compared. This can lead to the two languages giving opposite results with the same comparison.

    if ('04' == 4) // true in JavaScript but false in PHP
    if (04' === 4) // false in both JavaScript and PHP

    Quote Originally Posted by Philip M View Post
    In my experience it is not common to wish to compare two variables of different types.
    In my experience based on the questions newbies keep asking it is extremely common. Also because JavaScript is weakly typed once you get beyond a really simple script it starts to become more difficult to keep track of exactly what type a given variable currently is.


    Quote Originally Posted by Philip M View Post
    If a form field value is a number it should be converted from a string value to a number by one of several different methods at the outset. If it is a string then == is still fine, indeed === is pointless if both variables are known to be of the same type.
    Exactly my point - but you don't always now what type a variable holds at a given point in time and so when using == != > < etc you should always convert any variable to the required type before using it in the comparison. Few people actually do that which then leads to lots of problems that they could have avoided had they used === and !== instead.

    Newbies don't know JavaScript well enough to avoid the problems associated with == and != and so they should avoid using those comparisons until they learn enough JavaScript to use them correctly (with appropriate type conversions always included).

    If doing lots of comparisons for the same variable then using a switch statement (which always uses an implied ===) is better than a string of if/else calls.


    As far as newbies are concerned it is far easier to tell them not to use == and != than it is to explain the situations where using them is appropriate and how to perform all of the possible type conversions to ensure that they will work correctly.

    In fact where == comes in most useful is for validating whether a variable is or can be converted to a given type. For example the following tests for numeric.

    if (+n == n) // n is or can be converted to a number
    if (+n === n) // n is a number


    In fact that == example is proof that comparing variables of different types is something that is often done - it just happens to be one where you specifically want to allow for different types.
    Last edited by felgall; 01-08-2014 at 08:46 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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