1

In JavaScript, is there any significant difference in performance between querying a boolean variable's value or testing for the equality of two strings.

For example, which of these, if any, is more efficient:

Boolean example:

var testBoolean = false;

if (testBoolean) {
   alert('false')
}

String example:

var testString = 'false';

if (testString !== 'false') {
   alert('false')
}

Thanks!

3
  • Boolean is faster as you have one less comparison to make. You already have test set to false, but in second case you need to do string compare and push the result of that into the IF condition (which is the same as case 1 from here on) Commented Sep 4, 2014 at 16:46
  • Note that the 2 snippets aren't equivalent. The 1st will fail the if condition. The 2nd will pass and alert(). Commented Sep 4, 2014 at 16:47
  • Thanks for pointing that out Jonathan, I've now edited the question. Commented Sep 4, 2014 at 16:51

1 Answer 1

1
var testString = 'false';

if (testString === false) {
   alert('I'm inside the if condition')
}

This will never go into the if condition because '===' and '!==' operator check both the value and the type unlike '==' and '!=' operators. But I think that is not your question.

Boolean is faster as you have one less comparison to make. You already have test set to false, but in second case you need to do string compare and push the result of that into the IF condition (which is the same as case 1 from here on)

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

1 Comment

To your 1st point about type, both values are strings. Assuming the use of 'true' as well, the condition could pass.

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.