0

I came across some javascript code I don't understand:

what does a < 5 mean if the variable a holds a string?

Thanks

1

3 Answers 3

3

If a holds the string representation of a number, JavaScript will implicitly convert it to a number and perform the comparison.

Otherwise, it will return false.

For example:

var a = 'foo';
(a < 5) // will be false
(a > 5) // will be false

a = '10';

(a < 5) // will be false
(a > 5) // will be true
Sign up to request clarification or add additional context in comments.

3 Comments

If a is null or undefined and other variations , refer ECMA Specs for JavaScript comparison bclary.com/2004/11/07/#a-11.9.3
Even if the string doesn't represent a number, it will be converted to Number, e.g. in your var a = 'foo' snippet, the string 'foo' gets converted to NaN, and if one of the operands is NaN false is always the result.
Don't forget to mention truthy vs true, as exemplified in my answer.
0

Same as if it held a number, due to JavaScript's (occasionally twisted) type conversion rules.

That said, code that relies on that always makes me a little twitchy; IMO it should be converted to a number manually so it can be sanity-checked under more-controlled conditions.

Comments

0
var a = '5';
a   < 5;  // false
a   > 5;  // false
a  == 5;  // true
a === 5;  // false   <-- pay attention


var a = 5;
a   < 5;  // false
a   > 5;  // false
a  == 5;  // true
a === 5;  // true    <-- pay attention


var a = 'anythingelse';
a   < 5;  // false
a   > 5;  // false
a  == 5;  // false
a === 5;  // false

Comments

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.