Evaluation with untyped languages

October 21, 2008 — Leave a comment

When using JavaScript or PHP you need to keep in mind that these aren’t typed languages. Typed languages give us a lot of restrictions whilest keeping us from doing stupid things. Untyped languages do not have those restrictions so they leave us with a lot of freedom. Do we need this kind of freedom?

# Problem #

A typed language defines types (such as integer, string, boolean, …) to variables – that way the contents of variables are clearly defined. When not having this restriction (as JavaScript doesn’t) one might do the following (JavaScript code):

var alpha = 'This is some String';
alpha = 5;

Most of the time this is OK, but there are times when you clearly need to know how values are evaluated. You might check for content if you need to do special things for special types. Let us assume you want to assign alpha a default value if it is empty (''). Your code might look like this:

if(alpha == '') {
    alpha = '-';
}

This is perfectly OK if alpha is a string.

Nevertheless, alpha could always be an integer, too. And strangely, when the value of alpha is 0 (zero) the boolean expression alpha == '' evaluates to true! So alpha would become '-' in our case, which is not exactly what we intended to do, right? This could lead to some serious errors in your programme flow.

# Solution #

What can you do about it? Is there anything you could do? Yes, there is. When operating with values like '' (empty string), true/false (boolean contents of variable) and 0 (zero) you should always use the strict equivalence operators: === (equals to and same type) and !== (not equals to or not same type). The above code would then look something like this:

if(alpha === '') {
    alpha = '-';
}

That small change effects the semantics of the code. It now sets the default value if and only if the value of alpha is equals to '' and the type of alpha is the same as the type of '' (which is string, respectively). In fact, this is what you wanted to do, isn’t it?

If you use strict equivalence operators correctly then you can make sure the code does what you want it to do. Keep this in mind if you like writing correct code using untyped languages.

# See also #

Here are some useful links for JavaScript and PHP:

* JavaScript – Comparison Operators
* PHP – Expressions

No Comments

Be the first to start the conversation!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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