Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Javascript type conversions are happening here?

I found a bug in a script that was written, and I'm having troubles figuring out exactly what is causing the issues. Specifically:

"49px" < 50 === false

There's two different conversions I can think of here:

49 < 50 === true
"49px" < "50" === true
"49" < 50 === true // just for the hell of it

I fixed it with:

parseInt("49px") < 50 === true

So why does this evaluate to false? What exactly is happening here?

like image 349
Matthew Scharley Avatar asked May 13 '11 00:05

Matthew Scharley


People also ask

What are type conversions in JavaScript?

Type conversion (or typecasting) means transfer of data from one data type to another. Implicit conversion happens when the compiler (for compiled languages) or runtime (for script languages like JavaScript) automatically converts data types. The source code can also explicitly require a conversion to take place.

What are the types of type conversion?

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting. Explicit type conversion can also be achieved with separately defined conversion routines such as an overloaded object constructor.

How do you check what type a variable is in JavaScript?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.

Is type conversion possible in JavaScript?

You can also convert one data type to another as per your needs. The type conversion that you do manually is known as explicit type conversion. In JavaScript, explicit type conversions are done using built-in methods.


1 Answers

If one operand is a number and another operand is a string, then the string is converted to a number and then the comparison is made.

If the string cannot be converted to a number, it gets converted to NaN, and the comparison always returns false.

like image 59
GSerg Avatar answered Sep 21 '22 03:09

GSerg