JavaScript: the good part, the bad part

12:39 PM Xun 2 Comments

Recently (belatedly) I stumbled upon the excellent speech JavaScript: The Good Part" by Doug Crockford. There, like a mouse chasing cheese, I followed the trail
of "JavaScript: The Good Part", I devoured the book, I checked out the blog, I went through the slideshow. All of them by Doug Crockford.

By the way, if you do not know who this Doug Crockford is (after all, in our tech world, we are often more obsessed with products with funny names, twitter, lulu, hulu ...,
than the people who are behind the products), he is the one who "discovered" JSON. Actually, he was put off by the eccentricities of JavaScript first, then in working with
JavaScript further, he reliased the effectiveness and expressiveness (the good part) of JavaScript, thus the book. In a moment of "Aha", he also realised the
power of JavaScript literal notation, thus he set up json.org to publish and promote JSON.

Now back to JavaScript.

The Bad Part

Global Variables


The greatest evil of JavaScript are global variables. Global variables are convenient in a small program, however can be too quickly, easily, accidentally or intentionally
turned into a nightmare. First, global variables are slow; second, they can be easily overwritten and manipulated (an invitation for crosssite javascript attack);
third, variables are by default global, which makes them so evil.

Global Variables can created in the following three ways:

a) Proterties added to the global object (the window object)

window.x = 0;

b) Variables created outside a function


var x =0 ;



c) Variables created accidentally, i.e., variables being used without being declared,


x= 0;


or

var x = y = 0; // in this case, y becomes the accidental global variable because it is not declared first



adds and substracts and concatenates

JavaScript has very few primitive data types (number, string, boolean, object). Pretty much everything falls into the category of JavaScript; JavaScript also
does not require/need you to specify the data type of the variable; JavaScript also has a high tolerence for operating (adding, concatnating) on variables of different types. All of
which contributes to the sometimes strange behavior of adding and concatenating.

What will you get if you this?

0 + "1" // return "01";
"3" + 1 // return "31"


What happened? Because there is a string in the adds, JavaScript interprets as you want to concatenate two strings.

"3" -"2" // return 1

What happened? JavaScript assumes no substraction should occur between two strings, thus convert them to numbers for you!

JavaScript simply tries too hard.

Semicolon insertion

Another manifestation of JavaScript's evil is in Semicolon insertion. This again results from that JavaScript does scream or yell when you write
bad code (eg., forget your semicolon), however from behind the scene, it tries to remedy this by inserting the semicolor for you.

So what will you get for the following:

function add(a,b)
{
return
a+b
}



Oh-oh, you get nothing. Because JavaScript tries too hard by adding semicolons everywhere there is line break:

function add(a,b);
{
return;
a+b;
}


So please write your code correctly. Good style matters.

function add(a,b){
return a+b;
}



typeof

JavaScript let you check the type of your object by using typeof. Somehow, the typeof does not always act rationally either.

Try the following test:

typeof null === "object"; // returns true. But should it not be null type?
typeof [] === "object"; // returns true. But should it not be array type?

with and eval

with is bad. eval is evil. People all say so.

with is slow and confusing.

eval is slow too. It also can become an easy target of crosssite javascript attack.

phony arrays

JavaScript arrays are really hashtables that is accessed by the keys. This made it a bit slower.

== and !=

Because JavaScript's habit of type coersion, it is not easy to determine two things are indeed equal or otherwise with == and !=. The recommendation is using === and !== instead.

Consider the following, what will you get?

"1" == 1 //returns true  
1 == "1" //returns true
"" == "0" //returns false
NaN == NaN //returns false
NaN !== NaN //returns true



false, null, undefined, NaN, ""

Another bad part of JavaScript is that it has too many indistinguishable fals-y values: false, null, undefined, NaN, "", they all mean one way or another, false (as opposed to true),
no value /empty object (null), do not know what you mean (undefined), not a number (NaN), empty string (""). But, gosh, aren't they confusing?

The worst of them all is NaN, it is not a number, at the same time, it is a number. It is just, ah, not a number that is valid.


You may want to continue with your list about the bad that is JavaScript ...

Now, the Good Part.


That JavaScript is thriving today and becomes the most important language as it is the langugages of browsers testifies the goodness of JavaScript,
that it transform itself in the multiple excellent libaries such as JQuery and Ext.js and YUI while Java Applet failed without a trace says the effectiveness
and efficiency of JavaScript.

Its virtue must be numerous.

Functions

The best part of JavaScript is its extreme flexibilities of functions.

Functions are first class citizens (VIPS) in JavaScript. It can be used as you normal procedural functions;
a member method in an object; constructors. It can be anonymous, then the trendy name of lamda functions; it can be self-evoking; Functions has varying
depth of scope. You can create closures with functions ...

Procedural function

function add(a, b){
returns a+b;
}


Function as a member method:

  var addThem = 
{

add : function(){
return 1 + 2;
}
}

alert(addThem.add());


Functions as constructors:

 var Add = function (a, b) {
this.add = function () { return a + b };
}

var addMe = new Add(1, 2);
alert(addMe.add());

Anonymous Functions:

We often see them in event handlers and ajax calls:
 $('#target').click(function() {
alert('Handler for .click() called.');
});


 $.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});



Closures

Closures has been a mysteriously widely used word. What does it mean? In my understanding, it means an outer function create a closed
context where there are a set of variables that can only be accessed by its inner functions. This is the base for creating private members in
JavaScript. For example:

 function Add(a) {
var b = 2;

var add = function () { return a + b; }
return add;
}

var addNow = new Add(2);

alert(addNow());


Loose Typing:

In most languages, strong typing is strongly encouraged, because it gives you a sense of security that all of your variables are correctly typed, therefore type-related errors
can be easily found out and avoided. However, Mr. Doug Crockford said no. Strong-typing does not save you from good-old testing, besides any type
related errors can be easily found out. With the loose typing of JavaScript, you loose the rigidity and headache and overwork because you have to always
make sure you are on the correct side of types, it is libarating.

Agreed.

JSON

Last but not the least. JavaScript gives us JSON. The lightweight transimission of data. The now universal standard.

2 comments:

  1. Although I am in the process of learning JavaScript, this article is a huge enlightenment for me. For example, I noticed that the author of the book dropping some of the semicolons in the source code of some examples in the book but yet when I run the code it works flawlessly because he takes very good of formatting/styling his code. I know this might be just another typo but it made me confused at first but now I know the mechanism behind all of this

    ReplyDelete
  2. thank you for the wonderful comments. That made my day.

    ReplyDelete