0

This is something weird that started happening recently.

function someFunction() {
    return 0;
}
if (someFunction() == 0)
    runCode();
elseif (someFunction() == '0')
    runOtherCode();

In this situation runCode() will not be called but instead runOtherCode() will be called. Any reason why this is happening?

Edit: Using === fixed this error in some situations. However the other time this issue was present was when returning integer results from a database. For some reason the integers where being converted into strings but adding (int) to the data before returning the data fixed that error.

3
  • Even it were true that the result of someFunction is converted to string, it wouldn't matter. You are comparing using == which does not check the type and thus '0' == 0 evaluates to true ('0' === 0 however does not). Commented Sep 27, 2014 at 0:04
  • For us to be more helpful it may be handy to post your actual code here. Unless this is, of course, your actual code. Commented Sep 27, 2014 at 0:04
  • 1
    something is wrong elsewhere, check this demo 3v4l.org/tsDPj Commented Sep 27, 2014 at 0:12

1 Answer 1

1

You need to use strict comparison to prevent type coercion. Basically like this:

if(someFunction() === 0) 
elseif(someFunction() === '0')

3 equal signs instead of two invokes a strict comparison and is the only way to differentiate between string and integer comparison.

Edit: This is also relevant in other cases, so always consider it.

Sign up to request clarification or add additional context in comments.

10 Comments

Using loose comparison == 0 should still evaluate to true though, in OP's question.
Ahh. Wow. It seemed like that was obviously the problem, since that evaluation doesn't really make sense does it? I ran his version of the code and it works just fine. It still may have to do with strict comparisons, if he didn't post the exact code, but thought this was an equivalent example.
Yeah my initial thinking too ;) That's why I asked OP for his actual code, because I feel that there may be more to it.
This solved half my problem. The other half was integers from my database where being converted to strings for some reason. Now I just have to convert them back before returning.
Is your database column set to int or var? If the column always accepts integers, you should always make it an int column if possible, because it's processed faster (I'm talking about sql, but assume this is the case in pretty much all databases).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.