Reminder: run regsvr32 as Administrator

Always run regsvr32.exe as an administrator. It’s just so easy to forget, especially these days when COM interop is becoming a lot less common.

It’s a bummer that regsvr32 just quietly pretends like nothing when registration didn’t quite work as it should..

Command line illustration

Always run regsvr32 under an Administrator account

#6 NaN numbers in JavaScript

Numbers in Java are actually 64-bit floating point numbers, better known as the “double” datatype in C#, Java and probably C++ and C (I’m not sure it’s standardized in those languages though). They are based upon the IEEE 754 floating point standard.

One curious fact about JavaScript numbers is that due to the technical implementation every representable number can be both positive and negative. This is not so strange for numbers like 1 or -2.5, but it is a bit odd that you can have both positive zero +0 and negative zero -0, which of course is meaningless. But possible in Javascript.

Of course this post is specifically about NaN, the  “not a number” symbol.

NaN can appear in several ways, for example:

0/0
>>> NaN

parseFloat("bread")
>>> NaN     // oh right

NaN - 1
>>> NaN

Technical aside: In the IEEE 754 standard 64-bit NaN is represented by the number 2^53 – 2. But this is actually not the case in JavaScript, where NaN is a symbol separate from the range of numbers:

Math.pow(2,53) -2
>>> 9007199254740990     // ~9007 trillion or billion depending on your country

Ok, so how do you manage NaNs in a good way? One tricky aspect of NaN is that NaN is never equal to itself, so at first glance using comparison operators is pointless:

NaN === NaN
>>> false       // ?

NaN !== NaN
>>> true        // strange, but more on this later

A built in way of detecting NaN is by using the isNaN function. However, you have to know exactly what you are doing. There are pitfalls:

isNaN(NaN)
>>> true

isNaN(undefined)
>>> true       // seems like a bad idea

isNaN('a')
>>> true       // seriously?

isNaN('10')
>>> false      // ?

A neat trick in JavaScript is to exploit the property shown earlier that NaN !== NaN evaluates to false. In other words, we are exploting the fact that NaN is the only built in value which is always “not equal” to itself.

So comparing a variable to itself using the “not equals” operator is good way of determining if that variable is NaN or not. However, it could be infinity as well!

var a = 1.4,
    b = 1/0,  // infinity
    c = 0/0;  // NaN
a !== a
>>> false

b !== b
>>> false

c !== c
>>> true

#5 Binary logical operators in JavaScript

Binary logical operators like && (and) and || (or) are another area where things get a bit strange in JavaScript.

In other languages we are used to expressions of || and && to evaluate to boolean values. Here is an entirely made up example in C#, which would look very similar in Java:

bool result = hasTimedOut || (hasReceived && initialValueSet);
// result will always be true or false

In JavaScript, however, it is not the case that || and && return a boolean value. Instead these operators evaluate each of their operands, then return the value of the chosen operand according to the rules of the operation.

Now, if the value of all the operands are Boolean then no problem. However, if the operands are something else, like Number, String or Object, then you might get one of those as the result of the expression.

"this" || "that"
>>> "this"

0 || "1"
>>> "1"

The operands are of course converted to true or false using JavaScript’s conversion rules when evaluating the statements, but the returned result is the value of the operand and not it’s truthy or falsy value.

This property of || is used a lot for supplying default values when you are unsure if a value is undefined or null:

var myObj = myObj || {};

However, it can be very dangerous to depend on this mechanism without considering that some values may be zero, an empty string or similar for a good reason (all of which would evaluate to falsy). In these cases you might get the default value more often than you intended:

// myParameter will become 1 if undefined, null or 0 (zero) is encountered.
var myParameter = myParameter || 1;

var myString = myString || "none";  // will never allow myString === ""

Source: conversation with colleagues and the ECMAScript specification, page 83.

#4 Strings in JavaScript, part 1

Strings are sequences of characters, in other words texts.

Since JavaScript does not have a separate character data type, characters are represented as Strings having just one letter.

var char_c = "c";

You can use either single or double apostrophes for new strings.

var s = 'hello';
var t = "hello"; 

You can also split strings over multiple lines in code using a backslash immediately followed by a newline. This will not insert a newline when you output the string, so you have to use a “\n” if you want a newline to be output. Splitting strings over multiple lines carries some degree of risk, since it is easy to mess up the trailing newline.

var s = 'this string \
is formatted across \n multiple lines \
in the code.'

The aformentioned string might be output, say in a PRE-tag as:

this string is formatted across 
 multiple lines in the code.';

Like in C# strings in JavaScript are immutable. So for instance each time you concatenate two string you are in fact creating a new string.

var s = "hello ";
s = s + " world";   // s is now a reference to a different String object than before

#3 Prototype-based inheritance in JavaScript, part 1

It’s a well known thing that JavaScript does not have classes and regular object oriented features like we are used to to from languages like C# and Java.

Instead, in JavaScript each object is an extension of another object called it’s prototype. Each object has exactly one reference to a prototype object. This reference may also be null, which is the case eventually for all chains of prototype references.

For example, using Google’s Chrome browser I got this prototype chain for a commong String:

var str = "hello";

“hello” : String –> “” : String –> {} : Object –> null

1. First off, str is a reference to a String object, containing the primitive string value “hello”.
2. This String object has a prototype, which is another String object. However this String object is an empty string.
3. The empty String has a prototype, which is an empty Object (called the standard built-in Object prototype object).
4. The empty Object’s prototype is the primitive value null.

 

The way JavaScript resolves property accesses, functions and the like is by first searching in the object you are referencing. If not there then the prototype object is searched. It continues like this all the way until it reaches the “null” prototype reference (like we saw for the string object).

 

So an important difference between regular object orientation and prototype-based inheritance is that the prototype is always a separate object instance.

Now, if you create a new object but do not explictly set it’s prototype, then the “standard built-in Object prototype object” is used. This can have some odd consequences..

 

Since the same object is used for default prototypes all through JavaScript, what happens if you add something to this standard built-in Object prototype object ? It should appear everywhere right ? 

 

I did some testing using the debugger in Chrome:
Let a be a new object by using object literal notation. It does not have a test() function yet:

var a = {};
a.test();
>>> TypeError: undefined is not a function

Now, add a silly test function to a’s prototype:

a.__proto__.test = function () { return "xyzzyx"; }
a.test();
>>> "xyzzyx"

However, “b” also gets the same standard object prototype, and therefore the same test() function as “a”:

var b = new Object();
b.test();
>>> "xyzzyx"
var c = "another string";
c.test()
>>> "xyzzyx"   // oops, seems it's contagious..

Even the global object will have the test() function through it’s prototype:

test();
>>> "xyzzyx"

Prototype-based inheritance is a strange and different world as compared to regular object orientation.

#2 The global object in Javascript

Whenever you run some JavaScript code, the global object has been created for you as part of the execution context. By using functions and properties on the global object you perform most, if not all, of the most basic operations in Javascript. You can also add objects to the global object, but this should only be done to a very limited degree. This is to avoid clutter and accidentally overwriting existing values there. In short – to avoid making a mess!

Here are some examples of using the global object:

 

Get the value of the “undefined” value property on the global object, which returns the primitive type undefined:

undefined
>>> undefined

 

Call the “Object” function on the global object, which returns a new empty object:

Object()
>>> Object {}

 

Call the “parseInt” function on the global object, which returns a new Number object:

parseInt(4)
>>> 4
typeof parseInt(4)
>>> "number"

 

Call the stringify function on the JSON object which is a property of the global object:

JSON.stringify('hello')
>>> ""hello""

 

As opposed to the JSON object the global object itself is “invisible”. Just by typing something the JavaScript runtime assumes you are trying to access something on the global object. More on this and function scope later.

#1 A list of language types in JavaScript

I’ve written a good amount of JavaScript before, but I want to get a deeper understanding of the language. I’m guessing it will take a few dozen posts, but who knows really? I’m also hoping this will be a readable series of posts by the end. So without further ado.. :

Language types in JavaScript

Each value used in a JavaScript program is of one of the following types:

Primitive values:

  • undefined
  • null
  • boolean
  • string
  • number

Built-in objects (not showing error objects):

  • Object
  • Function
  • Array
  • String
  • Boolean
  • Number
  • Math
  • Date
  • RegExp
  • JSON

In reality, primitive boolean, string and number values will be wrapped in built-in Boolean, String and Number objects when you are working with them. So for instance I don’t think you will ever access raw 64-bit doubles, but instead always be working with numbers through their “Number” wrapper object.

Filling out the list of built-in objects there are the built-in error objects:

  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError