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

Previous topic in this series: JavaScript – A different beast!

This is the second part of my tutorial on JavaScript. Focus of this series is to introduce developers who are comfortable with other programming languages like Java or C to the idiosyncrasies of JavaScript. Basic JavaScript knowledge is assumed, but is not necessary as the code samples are simple and self-explanatory.

Topics:

  1. A different beast
  2. JavaScript Types and Type Conversion
  3. Functions
  4. Scopes and Scope Chain
  5. Closures
  6. Objects without Classes
  7. Inheritance without Classes
  8. Arrays, Maps and the for..each loop
  9. Literals and JSON
  10. Dynamic Programming, Exceptions and Module Pattern

The Language

Javascript is a dialect of ECMAScript. ECMAScript is the mother specification for a family of languages like JavaScript and ActionScript. All browsers implement some version of ECMAScript specification. The implementation is usually partial, which means that you will be surprised to see that your code does not run as expected on your browser. But don’t worry, we are going to deal with the stuff that works on most of the popular browsers today.

JavaScript is a scripting language and not a full-fledged programming language like Java or C. What this means is that it requires a host environment for functioning – usually a browser. (There are some initiatives to run JavaScript outside the browser)

JavaScript is an interpreted language and not a compiled one. It translates to two things for the developer: (1) Variables and functions should be declared before use – i.e. the code for declaration should come somewhere above the line where it is being used. See code – 1.1. , (2) Even syntax errors cannot be found without executing the code. So unless you execute each and every line of your code, there is no way of even verifying even its syntactic correctness – all the more reason to do Test Driven Development.

//Code - 1.1
doit(); //throws error: doit is not defined.
function doit(){ console.log('doing it'); }

Now before you get disheartened with declare-before-use behavior, take note that it works differently when there is a scope around it.  The same code works fine when executed within <script></script> tags  or within another function body. See code1.1(b).

<!--Code 1.1(b)-->
<html>
<head>
<script> <!-- Creates a new global scope -->
doIt();
function doIt(){ //function definitions are created first
alert('Doing it this time!');
}
</script>
<body></body>
</html>

This works because of the way functions are handled. A function declaration is always interpreted and bound in the scope before the actual code execution starts. [ECMAScript standard, section 10.1.3 explains this process]

1. Types

Type system in JavaScript consists of Primitives and Objects. Any value in JavaScript is an instance of either a primitive type or an object type

1.1. Primitive Types

See table below for all the primitive types in JavaScript along with the possible values.

Type Range Comments
Number 64bit floating point values and 3 special values : -Infinity,+Infinity and NaN (Not a Number) Same precision as Java’s double
String all string values
Boolean true,false

Note that JavaScript does not have separate integer numbers and floating point numbers. Its all just numbers – some have fractional part and some don’t have.
Special Numeric Values: Code -1.2 demonstrates how the special numeric values come into existence and also shows some functions to check for these special values.

//Code - 1.2: Special numeric values
console.log(3/0); //Infinity
console.log(isFinite(3/0)); //false

console.log(-3/0); //-Infinity
console.log(isFinite(-3/0)); //false

console.log('x'/10); //NaN
console.log(isNaN('x'/10)); //true

1.2 Object Type

Figure below shows the object type classification in JavaScript.

Objects in JavaScript
Objects in JavaScript

Host objects are the objects provided by the scripting host (browser). Built-in objects are implemented by the script execution engine itself (like a library) and therefore have browser specific implementation differences. User defined objects are the objects written by the JavaScript developer.The Function Object: The figure shows Function also as an object. JavaScript treats functions as ‘callable objects’ and can be passed around just like any other function.

1.3 Special Values – undefined and null

undefined and null are two special values in JavaScript both relating to the non-availability of an actual value. However, there is a subtle difference between the two. undefined implies that a value was never defined or assigned to the variable, whereas a null value means that the variable is assigned a value of null. See code-1.3.

//Code - 1.3: undefined vs. null
var newVar;
console.log(newVar); //undefined

newVar = null;
console.log(newVar); //null

1.4 Dynamic Typing

In JavaScript, variables do not have pre-defined types likes ‘name is a string’ or ‘age is a number’ etc. The types are determined by the value being referred to by the variable. Code-1.4 below demonstrates this. typeof is a runtime type introspection operator available in JavaScript which returns the runtime type information of the variable passed as its argument.

//Code - 1.4: Dynamic typing
var newvar = 10;
console.log(typeof(newvar)); //prints number

newvar = '10';
console.log(typeof(newvar)); //prints string

newvar = true;
console.log(typeof(newvar)); //prints boolean

newvar = new Object();
console.log(typeof(newvar)); //prints object

From this example we can see that the same variable is having different types based on its value.

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 (www.flickr.com/photos/rahulmohan/) 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: lamp.epfl.ch/~odersky/talks/pppj07.pdf)

  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 comment