I have written a good amount of Javascript, primarily using JQuery but I'm stumped on something very simple.
In the following code (also found here), I simply want to use the boolean return value of the twoExists() function in some logic. I have no idea why this behavior is happening, but it works counter intuitively. As in, if I switch the logic I get the result I want.
<html>
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>
<strong></strong>
</html>
var myJS = {
twoExists: function() {
$("p").each(function() {
if($(this).text() == "Two") {
return true;
}
});
return false;
},
foo: function() {
if(myJS.twoExists()) {
$("strong").text("Found two");
}
else {
$("strong").text("Did not find two");
}
}
bar: function() {
if(! myJS.twoExists()) {
$("strong").text("Found two");
}
else {
$("strong").text("Did not find two");
}
}
}
myJS.foo(); // result: <strong>Did not find two</strong>
myJS.bar(); // result: <strong>Found two</strong>
return false;So, it's finding two not because you switched but because the opposite of false is true. Try removing thetwofrom your options and see..