By DefaultPeak

2020-06-30 03:04:17 8 Comments

I'm currently trying to learn the basics of JavaScript and just wanted to ask a quick question about the || operator. You see, I'm currently reading through w3school's guide to JavaScript and I saw that || was paired next to &&, which is an operator I have used and understood. w3schools described it as being equivalent to "or". Since I had used && as a way of expressing several conditions in an if, I thought || would be to express several acceptable results. After I added it in one of my scripts from before, it didn't work at all.


function reply()
var answer = document.getElementById("questionPrompt").value;

if (answer == "Ok" || "ok") 
    document.getElementById("rightResponse").innerHTML = "Ok";
    document.getElementById("wrongResponse").innerHTML = "";
else {
    document.getElementById("wrongResponse").innerHTML = "Ok";
    document.getElementById("rightResponse").innerHTML = "";

<input id="questionPrompt"></input>

<p id="rightResponse" style="color:green;"></p>

<p id="wrongResponse" style="color:red;"></p>

<button onclick="reply();">Ok?</button>

As you can see if you test it out, no matter what answer you give it the text is green when it is intended to be red if you get it wrong. I am not sure if my issue is at a misunderstanding of ||'s purpose or if it is the code instead. If it isnt the latter, please make an effort to make it as understandable as possible to a beginner like me, because after looking this up, I was left confused because of the terminology-heavy explanations. Thank you!


@adamgy 2020-06-30 03:09:46

This is because answer == "Ok" is being evaluated first, after which the result is compared to "ok". Since "ok" is a truthy value itself, your comparison will always evaluate to True regardless of the input.

Try: if (answer == "Ok" || answer == "ok")

Related Questions

Sponsored Content

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6835314 View
  • 8412 Score
  • 96 Answer
  • Tags:   javascript arrays

37 Answered Questions

[SOLVED] What is the !! (not not) operator in JavaScript?

  • 2009-04-24 08:13:58
  • Hexagon Theory
  • 559949 View
  • 3146 Score
  • 37 Answer
  • Tags:   javascript operators

86 Answered Questions

[SOLVED] How do JavaScript closures work?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

3 Answered Questions

57 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

7 Answered Questions

[SOLVED] Why does Google prepend while(1); to their JSON responses?

Sponsored Content