This Just In: JavaScript is a Real Language

May 11, 2009

Some people think of JavaScript as that crappy language that runs inside of browsers. The truth is that the languages is not that bad, aside from a few warts (void, explicit return, global by default, I'm looking at you), it's pretty nice. I think it's gotten a bad rap for a few reasons.

First of all, the DOM. Before modern JavaScript libraries like jQuery and Prototype came along, developers were constantly pulling their hair out dealing with incompatibilities across different browser implementations of the DOM. Modern libraries have done a lot to normalize behavior across browsers and browser implementations have gotten better, but many developers still have bad memories of dealing with "JavaScript" back in the day. The truth was this wasn't really a problem in JavaScript the language, more so the DOM and browser implementations. If the language that Netscape put into the browser originally was Ruby, we would blame Ruby for all of these problems too.

Next, I think there was a whole class of Java developers upset that OO didn't work in JavaScript the way it did in Java. JavaScript wasn't considered a "real" OO language and was therefore inferior to Java. JavaScript has it's own way of dealing with OO and the sooner you understand how that works, the more comfortable you will be with JavaScript.

In the opposite way that many Java developers despised JavaScript, many Ruby developers, including Java developers converted to Ruby developers, started to appreciate JavaScript. JavaScript has anonymous functions just like Ruby has anonymous functions. Ruby makes ubiquitous use of anonymous functions through blocks. I think for many developers, Ruby was the first language they used that showed how useful anonymous functions can be. I think this is also the reason that you see some many Ruby developers interested other functional languages like Erlang, Haskell and Lisp.

Lastly, I think many developers don't see JavaScript as a general purpose language simply because it's trapped inside the browser. You can't run a JavaScript script from the command line just like you can run a Ruby, Python or Perl script.

Well, it turns out that last one isn't true and I want to show you how to get started writing some JavaScript as a "real" language, and specifically, a functional language.

The first thing you'll need is a JavaScript interpreter. There are many JavaScript interpreters available, such as:

  • SpiderMonkey, the C-based JavaScript interpreter for the Mozilla Gecko rendering engine
  • V8, the C++-based JavaScript interpreter for the Google Chrome browser
  • Rhino, the Java-based JavaScript interpreter.

Let's go with SpiderMonkey.

If you are on a mac and you want to get up and running with SpiderMonkey, the easiest thing to do is sudo port install spidermonkey.

If you want to build it from source, download the tarball and untar it somewhere on your machine. I did that in the src directory in my home directory. Then you go into the js/src directory and run the make command. Here's what that looks like:

cd ~/src
wget http://ftp.mozilla.org/pub/mozilla.org/js/js-1.8.0-rc1.tar.gz
tar xvzf js-1.8.0-rc1.tar.gz
cd js/src
make -f Makefile.ref

Now you should have a directory like Darwin_DBG.OBJ, it will be named differently if you aren't on a Mac. Inside that directory there is a js program you can run. To make life easier, add ~/src/js/src/Darwin_DBG.OBJ to your path, or create a symlink in /usr/bin to ~/src/js/src/Darwin_DBG.OBJ/js.

Now either way, whether you installed spidermonkey via mac ports or from source, you should be able to just type js from the terminal and be at an interactive JavaScript interpreter, with js> as the prompt:

$ js
js> print("Hello, World")
Hello, World

You can also run js my_awesome_script.js to run a script saved in a file. I have created a textmate bundle that has a run command for javascript files. If you install this, then you can press Cmd-R to see the output of the file.

So now let's write a little JavaScript. First things first, open a file called hello.js in Textmate and put this into it:

print("Hello, World!")

If you've created the command properly, you should see Hello, World! printed out. If you aren't using Textmate, then you will have to figure out how to get your editor to run the file. Even if you can't do that, it's as simple as running js hello.js from the command line.

Now we can write some real code. What we want to focus on doing is functional programming. Most of the basic functions for functional programming aren't defined in JavaScript by default, but it's easy enough to write our own that handle the basic things. Note that this kind of functional programming is going to be functional in that we are going to pass functions to and return functions from functions, a.k.a higher-order functions, but we aren't going to focus on other popular aspects of functional programming such as immutable data and pure functions. Baby steps. :)

So the first thing we need is some kind of implementation of an iterator function, because we're not writing for loops. Let's do something like Ruby's each:

function each(f, arr) {
  for(var i=0; i < arr.length; i++) {
    f.apply(null, [arr[i]])
  }
}

What this does is take a Function and an Array and applies the Function to each element of the Array. To test this out, let's also add this line of code to test it:

each(print, [1,2,3,4,5])

You can see that we can pass the print function to each and have it print the numbers from 1 to 5. Ok, next up is map, which takes a Function and an Array and returns a new Array which contains the result of applying the Function to each element of the Array.

function map(f, arr) {
  var result = []
  each(function(e) {
    result.push(f.apply(null, [e]))
  }, arr)
  return result
}

We can test that out with:

print(map(function(e){
  return e * e
}, [1,2,3,4,5]))

This time, we are passing an anonymous Function as the first argument to the map Function. This Function takes one value and multiplies it by itself, better know as square. Now for our last trick, we will do the functional programming equivalent of hello world, fibonacci:

function fib(n) {
  if(n <= 1) {
    return n
  } else {
    return fib(n-1) + fib(n-2)
  }
}

We can test this with:

each(print, map(fib, [1,2,3,4,5,6,7,8,9,10]))

Here's the entire code in one gist.

Now that JavaScript is being viewed as a "real" language, it's even got it's own conference! There's also some IRC channels devoted to JavaScript as well and of course, Stack Overflow. Happy JavaScripting!

Posted in Technology | Tags Rhino, SpiderMonkey, Javascript, V8

Comments Comments Feed

1. Argh! Don't use the for...in construct for array iteration! http://www.ruby-forum.com/topic/110060

# Posted By Greg on Monday, May 11 2009 at 2:58 PM

2. Of course JavaScript is a real language, in fact you could go so far as to say JavaScript is a real functional programming language! Its native support of closures and higher-order functions puts it in a league that most developers never even considered it to be capable of. Not sure if you heard, but the JavaScript projects displayed at JSConf will astonish many - Reasonably Smart platform, PhoneGap, Cappuccino (NIB->CIB), and many others. There are few other languages with as big of companies pumping as much money into its future development. Oh and unlike python and ruby, its interpreter has been on every machine since 1996.

BTW - you may want to include V8 (google's JS interpreter) in the listing above. http://kourge.net/node/123

Great article and thanks for helping bring awareness!

# Posted By Chris Williams on Monday, May 11 2009 at 10:03 PM

3. That's "bad rap" (as in prison sentence), not "wrap."

# Posted By Speaker-to-Animals on Tuesday, May 12 2009 at 12:17 PM

4. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 3:24 AM

5. Wonderful brian atwood shoes for your style.BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.
And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy!
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
I really love brian atwood nico patent pump.
And this year, brian atwood maniac pumps are so hot among stars, I saw many times that Victoria-Beckham wearing them on the show time.
If you don’t know about brian atwood…You should. When everyone else is obsessing over the latest pair of Loubs or YS’L’s it’s very easy to overlook awesome shoe lines and designers who push the envelope. brian atwood is one of those designers.I’m a fan of his lines because Atwood really sets out to make his shoes a conversation piece. The use of alternative textures and fabrics makes brian atwood shoes unique. When wearing his shoes you are guaranteed a compliment from someone and a definate shoe in for best footwear. So ladies (and gents) get into these! And I know my card carrying “Shoe Wh*res” are going to love these!
Buy brian atwood shoes at http://www.brianatwoodcom.com. Buy brian atwood pumps at http://www.brianatwoodcom.com/brian-atwood-brian-atwood-pumps-c-65_67.html.
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood lexia is worth the investment.
Back by popular demand... brian atwood maniac tan, the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. In a beautiful, very neutral nude tan.
brian atwood whip snake shoe with Exotic whipsnake hidden platform and back metal inset.
Take a walk on the wild side with Atwood Jagger printed knee-high boots. Style them knee high to add sass to an LBD or wear them with the fold-over flap turned up to work this season's hot over-the-knee trend.
brian atwood cage peep Price: $228. 140mm Covered heel. Rounded peep toe. 40mm covered platform. Interwoven cut outs around front. Ankle strap with adjustable metal buckle. Leather insole and lining. Leather sole. Made in Italy.
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood crystal court shoe is worth the investment.
Brian Atwood Platform Chain Pumps with A silver chain scales the lace-up back of this vamped-up pumps.
brian atwood snakeskin platforms is the classic and the elastic heel detail was used again from last Fall.
brian atwood patent leather and mesh Futuristic patent leather style with mesh details and contrast stitching.
Heel measures approximately 95mm/ 3.5 inches. Let your feet do the talking in brian atwood dorota shoes. Wear this chic style with off-duty denim or to liven up office looks.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 3:32 AM

6. A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 3:38 AM

7. Diamond earrings and tiffany silver bracelets can be a romantic gift for any occasion. These can be as simple as a single stone silver tiffany earrings or as elaborate as chandelier silver tiffany earrings embellished with numerous stones. It is important to keep in mind the individual you are buying the gift for. If the recipient of the gift would like something that they can wear every day, tiffany promise rings are the way to go. However if the gift recipient enjoys getting dressed up for a night on the town or goes to formal affairs on occasion, the chandelier tiffany inspired rings are the perfect gift.

# Posted By tiffany promise rings on Tuesday, August 31 2010 at 2:21 AM

8.

Cheap nfl jerseys are your best choice,a newly released innovative product that will discounted nfl jerseys help you in your sport, or a one of a kind toddler nfl jerseys collectible that you will keep in your family for generations.Quality first,infant nfl jerseys Customer forever, GUARANTEE SHIPPING is our persistent tenet.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:19 PM

9. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By nike dunk on Thursday, September 2 2010 at 2:11 AM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)