Thailandian
Thailandian

Reputation: 585

Why did my incorrect if statement work?

I recently came across the following syntax error:

if (button=="init" || "show_selected" || "show_all") {

Of course this should have been:

if (button=="init" || button=="show_selected" || button=="show_all") {

HOWEVER, the original statement seemed to be working perfectly in Chrome, FF and IE9!?!? I only chanced upon my mistake while adding a new option.

To clarify, "init", "show_selected" and "show_all" are string arguments used when calling the function; e.g.

onclick=myFunction("init");

I'm sure I remember trying this kind of shorthand early on when learning JS and finding out very quickly that it didn't work.

I've already corrected the code anyway, but it's annoying me that I can't see why it was working.

Can anyone shed light on this enigma?

Upvotes: -1

Views: 52

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

Of course it will work, and it will always work because your condition will be always true:

if (button=="init" || "show_selected" || "show_all")

Will always give true because "show_selected" is a string and if you pass it as an if statement condition it will be always true, your code is evaluated like this:

if (button=="init" || true || true) // Will always be true

Because writing if ("show_all") is equivalent to if ("show_all" !== null) which is true.

For example, try this:

if ("show_all"){ //returns true (the statement is true)
   alert(true); 
}

Upvotes: 1

Quentin
Quentin

Reputation: 943220

Your strings are expressions that are true values.

if ("show_selected") { /* ... */ }

… would run the code in the block.

You are using strings on the RHS of each of your OR statements, so the RHS of each is true.


Given:

myFunction("init");

Then:

button=="init"

Is:

true

So:

button=="init" || "show_selected" 
true || "show_selected" 
true

If you were to pass in any other value

button=="init" || "show_selected" 
false || "show_selected" 
"show_selected" 

Upvotes: 0

Related Questions