Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

JavaScript for OO programmers, Part 2 – Things to watch for

5.00/5 (2 votes)
15 Dec 2010CPOL1 min read 11.4K  
The second in a series of posts in which I will attempt to explain JavaScript from the perspective of an OO programmer.

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;

JavaScript
'' == '0'	// false
0 == ''; 	// true
0 == '0';	// true

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 strings. 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 string0' to the numeric value 0. That comparison would return false in C#.



Filed under: CodeProject, JavaScript, Web Development

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)