Thursday, June 13, 2013

JavaScript Primitives, The Imposters!!!

Allegedly the JavaScript universe contains 5 primitive types:
  • string - a sequence of unicode characters
  • boolean - represents a truth value of true or false
  • number - represents any number, even really big ones, between -253 and 253
  • undefined - indicates that a property or variable is unknown, does not exist
  • null - indicates no value
I say these primitives are imposters! They behave like objects but are not. JavaScript being a loosely typed language morphs the primitives into objects when used as objects. These primitives also have object wrappers.

var primitiveString = 'I am a primitive string';
var objectString = new String('I am a String object');  //using the object wrapper

primitiveString.length;   // 23, will work and return the correct value like an object


You could even do this

primitiveString.myvalue = 'test'     //like an object

which assigns the value 'test' to a hidden object property that you have no reference to, so you can't access the property from the primitive type thereafter.

null and undefined are also very strange, since they are just properties of the global object and can be redefined by you, but please, don't do that. More on this later.

Whether you use objects or their imposters, doesn't matter, just be consistent, so as to avoid hard to find bugs. Next, I play with JavaScript's awesome arrays, until then, may the code be with you.......

Part 3: JavaScript Object Oriented Fundamentals

No comments: