简体   繁体   中英

Can't wrap my head around the behavior of this logical operator

I was messing around with some simple exercises and found something that I thought acted quite odd. I wrote a very simple HTML form that when a user enters their name, if it was Bob or Alice it would great them. If it was another name, it would say I don't know you. So, my thought was to use a logical operator to compare the username that was entered. Here is my code:

<h1>This is the practice space</h1>
    <div id="output">
        <label>what is your name?</label>
        <input id="name" type="text">
        <button type="button" onclick="getName()">Send it through!</button>
        <span id="output-name"></span>
    </div>

    <script>
        function getName(){

            var userName = document.getElementById('name').value;

            if(userName === 'Alice' || 'Bob'){
                document.getElementById('output-name').innerHTML = 'Hello ' + userName + '! Glad to have you!';
            } else {
                document.getElementById('output-name').innerHTML = 'I don\'t know you.';
            }
        }
    </script>

To me this says "if userName is equal to Alice , then true, If not, if userName equals to Bob then true. If not, then I don't know you. That is not the case. Everything that I enter is passing as true and nothing is passing as false. Can anyone make any sense of this?

By the way, I read through the documentation on MDN specifically to find out the logic in these logical operators. I thought by what I read, my code should work.

That is because you're not checking anything against 'Bob' .

Change:

if(userName === 'Alice' || 'Bob')

To:

if(userName === 'Alice' || userName === 'Bob')

The reason your current code returns true all the time is because strings, unless empty, are truthy . 'Bob' evaluates to true , so your if statement is quite literally saying: If the username is equal to Alice, or if this is true, then... . if ('Bob') will always be true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM