JavaScript, as we shall see, has many peculiarities which distinguish it from languages that OO devs are familiar with. Being aware of these peculiarities will help you, dear reader, in navigating the labyrinthine foibles of my favourite programming language. Therefore, I shall attempt herewith to enumerate these vagaries, that you may not fall into the fiery pit of despair and instead ride the chocolate rollercoaster to the squeaky-clean apogee of true JavaScript demigod, total spiritual creaminess and avoid the chewy chunks of degradation.
#1: Equals
Take the piece of code below;
'' == '0'
0 == '';
0 == '0';
Screwy right? The reason for this particular little piece of craziness is that the double equals operator in JavaScript implies Type Coercion. What this means is that it behaves correctly when the values are of the same type, but when they are not, it tries to convert the value on the right hand side of the comparison to the type of the value on the left. In the above example, the first expression evaluates as it should because both operands are string
s. In the second example, it converts the empty string
to the number equivalent 0
because it is a ‘Falsy’ value (more on falsy values later). And in the last example, it simply converts the string
’0
' to the numeric value 0
. That comparison would return false
in C#.
CodeProject Filed under:
CodeProject,
JavaScript,
Web Development