JavaScript – A Different Beast, Part 2: Types and Type Conversion

1.5 Type coercion and evaluation

Dynamic typing produces some tricky results when used with operators that expect some type. For example, the statement z = x + y in JavaScript gives different results based on the runtime type of the operands x and y. If both x and y are numeric, then the + operator works as arithmetic addition, whereas if both x and y are strings, then it behaves like string concatenation. See code-1.5 below.

//Code - 1.5: Operator overloading
 function f(x,y) {
 return x+y;
 console.log( f(3,4) ); //number 7
 console.log( f('3','4') ); //string '34'

Now, think of what would happen if one of the operands is numeric and the other string. In such cases, JavaScript takes the liberty of evaluating one of the operands to an equivalent value of the required type. In this case, the numeric operand is evaluated as a string resulting in string concatenation. Code-1.6 shows more such cases using division operation. Since division is an operation that requires both the operands to be numbers, JavaScript tries to convert any non-numeric argument to its numeric equivalent.

//Code - 1.6: Coercion to number
console.log('10'/'2'); //5. Both evaluated to number
console.log('10'/2); //5. '10' evaluated to number
console.log(true/2); //0.5, true evaluated to number 1
console.log(false/2); //0, false evaluated to 0
console.log('Apple'/2); //NaN, 'Apple' cannot be evaluated to a number

Such type of automatic conversions of values often results in errors in the code, unless the developers are very clear about these concepts. Code-1.7 below shows some common mistakes in addition and comparison.

//Code - 1.7: Common conversion mistakes

//String vs. Number
console.log(2 + 8); //10, numeric. OK
console.log('2' + 8); //28, string
console.log('2' + 3 + 5); //235, string

console.log('banana' > 'apple'); //true, lexical comparison
console.log(123>33); //true, numeric comparison
console.log('123'>'33'); //false, lexical comparison used

Chances for such mistakes are very high when the values are coming from a textbox or from a server response that came as XML or JSON. Programmers should always take care to establish the correct type to the value before being passed to functions that do such operations. Code-1.8 below shows an example of string to number conversion using parseInt.

//Code - 1.8: Establishing correct type

var left = '123';//could have been document.getElementById('left');
 var right = '33';//could have been document.getElementById('right');
 console.log(left > right); //wrong
 console.log(parseInt(left) > parseInt(right)); //correct

Automatic type conversion can also happen with the ‘==’ operator. Code-1.9 below shows some other scenarios.

//Code - 1.9:  Automatic type conversion
console.log(10=='10'); //true
console.log(1==true); //true
console.log(0==false); //true

//use === instead - 'exactly equals to'
console.log(10==='10'); //false
console.log(1===true); //false
console.log(0===false); //false

//be careful of if(),while etc
if(1) console.log('TRUE'); //TRUE
if(0.5) console.log('TRUE'); //TRUE !! told you to be careful!

The ‘==’ operator does type conversion and evaluates 1 as true, 0 as false, 0.5 as true etc. Fortunately, JavaScript has an ‘exactly equals to’ operator written as ‘===’ which brings can bring some sanity to the code. Conditional statements like if/while etc which expect boolean arguments also automatically convert the supplied argument into a boolean value. 1 as true and 0 is false is still fine, but 0.5 becoming true is definitely a stretch on the programmers’ imagination! My advice: avoid writing code that works on such idiosyncrasies, if you want other programmers to understand your code.

Next Topic in this series: Functions


  1. An excellent reference for learning all about numbers – Must read this if you are developing financial applications where you have to deal with money of various precisions.
  2. Read this for a detailed explanation on type conversion logic in JavaScript.
  3. The authentic specification document. As all specifications go – unreadable!

About Rahul Mohan

Technical researcher interested in model-driven development of enterprise business applications. Passionate about web technologies and a huge admirer of open-source especially in the Java landscape. When I am not doing any of the above you can find me with my camera ( or listening to music. (In fact, the title of the blog is inspired by Led Zeppelin's Physical Graffiti. )

Posted on May 10, 2011, in JavaScript, Tutorial and tagged , , , , , , , , . Bookmark the permalink. 16 Comments.

  1. “functions should be declared before use” – This should be good enough to keep myself away from Javascript. Not sure if I understand the reason why it exists today !

    • Never thought that statement would scare someone. Actually, its not that scary when running inside browser. I have updated that section with some good news. Take a look.

      As to why JS lives on, the answer is quite simple:
      Problem: Everyone wants wonderful user interfaces on browser based apps. But, presentation primitives natively available on browsers are dumb (unlike the natives of android, iOS, Silverlight etc.)
      Solution: JavaScript is the only solution to this that will work on all browsers.

  2. I guess what you refer to as “Host Objects” are probably the primary source of confusion for beginners atleast. I find the beginners tend to refer to an API set as Language. For example, beginners tend to see the Host Objects as inherent to the Language Syntax rather than a set of API offered in Javascript language by the browser software to suite the needs of browser. Added to that, there seem to be probably many (2) flavors of accessing those objects (commenting out of ignorance).

    • >> “I find the beginners tend to refer to an API set as Language”
      True. But having said that, a cleverly designed library API makes the language a real treat to use. A case in point is C on Unix vs. C on Windows. The Unix version is so rich because of the availability of kernel APIs that developers don’t even look elsewhere if they have to code on Unix. The same is true with Java libraries as well. There is so much functionality already there! In fact, one of the newer languages called Scala builds on this idea and uses libraries as a way of scaling up the language (hence the name). I am planning to write on Scala soon. (For more on scala, see:

  3. Rahul

    I love your blogs.
    Happy to c u blogging again…

    I hope after completing Java script you will move on to more blogs about web development (esp front end).
    Because I believe a lot of programmers are good in back end stuff but very few web developers (not sure if it is just developers form India) has a thorough understanding how front end works. But as Steve Souders (High Performance Web Sites by Steve Souders, O’Reilly Media, Incorporated) points out 80% of the web performance is dependent on the front end software. Thanks for taking up a life problem and doing something about it.

    wish that your blog make at least a few websites less frustrating to use…

    • Glad you found it useful. A warning though: I am not planning to stay with just the client, will be talking about all that stuff (tech stuff, to be precise) that I see from my cubicle!

  4. Somebody essentially assist to make seriously articles I would state. This is the first time I frequented your web page and up to now? I surprised with the research you made to make this actual post amazing. Excellent task!

  5. So what can you do to fix your improper posture and back pain. Heck
    I’ve even done grueling work like new home construction, electricians apprentice, professional
    movers, hauling and professional truck driving. You often see advertisements on television for attorneys
    that are accepting cases for all kinds of lawsuits against different drugs and those responsible for manufacturing them.

  1. Pingback: JavaScript – A different beast « Technical Graffiti

  2. Pingback: Professional JavaScript, Part 3: Functions « Technical Graffiti

  3. Pingback: Professional JavaScript, Part-3: Scopes and Scope Chain « Technical Graffiti

  4. Pingback: Professional JavaScript, Part-5: Closures « Technical Graffiti

  5. Pingback: Professional JavaScript, Part-4: Scopes and Scope Chain « Technical Graffiti

  6. Pingback: Professional JavaScript, Part 3: Functions « Technical Graffiti

  7. Pingback: Professional JavaScript, Part-6: Objects without Classes « Technical Graffiti

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: