Another JavaScript Coding Question

Another JavaScript Coding Question

by W Page -
Number of replies: 2

Hello All!

I would like to understand the use of "||", that is "or" better in JavaScript.  I have be toying with the script below.  After I run it, I would like to get the response "true" but I keep getting "false".

  • Am I not using the "||" correctly?
  • Can I use "||" to get the response I want to get or should I,
    • Use something else?
    • Construct the script flow differently?

Thanks in advance for any and all responses.

WP1

<HTML>
<HEAD>
    <TITLE>
    JavaScript Example 2 - My Variable - Cat - Rat - Mouse
    </TITLE>
</HEAD>
<BODY>

   <SCRIPT TYPE="text/javascript">
 
        var myValue = "cat";
        document.write("Initial Animal is: ");
        document.write(myValue);
        myValue = "rat" || "mouse";
        document.write("<P>Then I saw a  rat, and the value is: ");
        document.write(myValue, "</P>");
        document.write("<P>But, is a rat similar to a mouse? ");
        document.write(myValue == "mouse")
        document.write("</P>");
 
    </SCRIPT>


</BODY>
</HTML>

Initial Animal is: cat
Then I saw a rat, and the value is: rat
But, is a rat similar to a mouse? false

Average of ratings: -
In reply to W Page

Re: Another JavaScript Coding Question

by Andrea Bicciolo -

W, while "==" is comparison, "||" is boolean, so "rat" || "mouse" evaluates "rat", thus fails your document.write statement.

"rat" && "mouse" --> "mouse" (And)

"rat" != "mouse" --> true (not equal)