Click here to Skip to main content
15,886,026 members
Articles / Programming Languages / Javascript

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
14 Dec 2010CPOL1 min read 11K   4   2
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)


Written By
Architect UBS AG
Switzerland Switzerland
Mel Padden:

Musician, papier maché guru, international authority on the modern crisp, and sometime software developer based in Zurich, Switzerland and Dublin, Ireland.

http://www.linkedin.com/in/melpadden

Comments and Discussions

 
GeneralMy vote of 5 Pin
JH6422-Dec-10 8:34
JH6422-Dec-10 8:34 
GeneralMy vote of 5 Pin
Kasyapa20-Dec-10 14:49
Kasyapa20-Dec-10 14:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.