Java Expert RE-Learning Javascript Part 2 - Operators

What do you thing, what does javascript do with the following ?

"5" + 1
- result? "51"
5 + "1"
- result? "51"
"5" - 1
- result? 4
"5" == 5
- result? true
null == undefined 
- result? true

How did you do? I was bad at it, especially to realize that "5" + 1 and 5 + "1" would make the same result. Javascript tries always to do conversion whenever the types of operands dont match.

Javascript is pretty easy-going language. It allows you to do many things, giving you a bit of additional freedom. BUT you have to be VERY careful, as you can imagine that in some cases, above mentioned freedom might cost you a lot of bugs :)

So, summary of rules in Javascript about operators:


  • If you give Javascript different types to operate with, it will start doing type conversion. The way it would do it is based on set of (often confusing) rules. It would check first the operator, and then try to convert operands to the type appropriate to the operator. However, Javascript sees addition operator (+) as string concatenaton first.
  • null and undefined in operation with numbers will convert to 0 and NaN respectively (examples: 8+null = 8 , 8+undefined = NaN)
  • In order to assure yourself that the two values are properly compared, you should rather use === instead of ==. === (triple equals), checks precisely if the values are equals, without doing any automatic conversions.


So, what is the difference between double equals and tripple equals? With "==", Javascript tries to do automatic conversion before comparing the values, and with "===", Javascript does the precise comparison, without trying to "be smart".

Now the most favorite new thing for me: Logical Operators!

The rule sof && and || operators are the following:

  1. Javascript will try to convert the left-hand value to Boolean type in order to decide what to do,
  2. depending on operator (&& or ||) and the result of that conversion, it will return either original left-hand or right-hand value.
  3. "" is converted to false, and "jklkjsda" is converted to true. 0 is false, and 3124 is true.
some examples:
"Carl" && "Bob"
"Bob"
"Carl" || "Bob"
"Carl"
"" && "Bob"
""
"" || "Bob"
"Bob"

Comments

Popular posts from this blog

Timeline on Latex

Exporting Skype Chat/Skype Contacts to csv file using the shell script and sqlite3 (usually already installed on mac)

trim() not supported by IE7 and IE8