Sunday, July 7, 2013

The Date Object

The first thing I notice about the Date object is that it keeps track of time in milliseconds since January 1, 1970. That's almost the way the Unix operating system keeps track of time. Almost.

However, Unix keeps time in seconds since 1970 rather than milliseconds.

The next thing I notice is that the Date object has over 15 get methods that allow you to get the time of day in various formats. For example, there is the getFullYear() method which will calculate the current year from the Date object. Here's how to print the current year using this method:

var dt = new Date();
alert(dt.getFullYear());

You can run the above 2 lines of code in a JavaScript sandbox. Just do a search on JavaScript sandbox using your favorite search engine.

The getTime() method returns a huge number, the number of milliseconds since January 1, 1970:

var dt = new Date();
alert(dt.getTime());

Currently, in 2013, that's over 1 trillion milliseconds.

So basically all the get methods are really conversion functions. They convert time from a raw number, such as milliseconds since 1970, to another number, such as the number of years since 1970.

I'm curious as to why JavaScript stores time in milliseconds rather than seconds. Why does Unix store time in seconds while JavaScript stores time in milliseconds? I don't have an answer to this question.

Ed Abbott

Thursday, July 4, 2013

Learning JavaScript

I'm learning JavaScript. JavaScript is very similar to Perl and to C++ in some respects. In other ways, it is quite different.

Computer languages come in families. That's the first thing I notice about JavaScript. It is very similar to a whole family of languages.

For example, JavaScript has a replace() method that is very similar to the substitution operator in Perl. Of course Perl borrowed its substitution operator from the s///g subsitution syntax of a Unix utility called sed. But sed seems to have gotten that same syntax from the old ed editor found in the very earliest versions of Unix.

So this business of borrowing syntax from one programming language in order to create a new programming language is a very pervasive one. Computer languages are very much like spoken languages. If a word in your native language will not suffice, than a word from a foreign language is borrowed instead

So, perhaps, that's the first lesson in JavaScript. If you can't quite find a feature you want to know more about, ask how to do it in another language. This can be helpful if you know so little that you don't even know what to call a feature.

For example, a common feature in scripting languages is search and replace. However, if you don't know that that's what it is called, it makes it harder to search for using a search engine such as Google.

The lesson? There's nothing new under the sun. Well, at least very little. Something that appears to be a startling innovation may have appeared elsewhere first.

Ed Abbott