Sample to understand Automatic Type Conversion in Javascript function test1(){
var result = (false == 0); //true
alert("test1: " + result);
}
function test2(){
var result = ("10" == 10); //true
alert("test2: " + result);
}
function test3(){
var result = (" " == 0); //true
alert("test3: " + result);
}
1) On test 1 you are comparing a type “Boolean” with an “Integer”, but Javascript will automatically try to convert the Boolean to an Integer to compare them, and if you didn’t know this True is a 1 and False is a 0.
This also happens in most of programming language because Boolean can always be converted to 0 and 1, they actually are 0 and 1.
2) The first value is a string, and the second one is a Integer, they shouldn’t be compared because they have different types, but JS will magically try to convert the string in to a number to compare them, if you try the same example with “hi” == 10 the result will be false.
3) Test 3 proves that JS is made to be simple, comparing an almost empty string with zero will result true. Logically to achieve this in some other languages you would have to trim the string (get rid of the white spaces) and then compare it with an empty string (“”), resulting in a Boolean and then compare that with zero.
References: http://karlmendes.com/2011/11/understanding-javascript-automatic-type-conversion/
https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-3/type-conversions
http://www.sitepoint.com/automatic-type-conversion/
Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif
Programmer123, if this helps please login to Mark As Answer. | Alert Moderator