What they don’t teach you in (W3)school: JavaScript variable scoping

January 27th, 2011

W3Fools is an interesting site I came across that highlights the wrong parts of W3Schools. While W3Schools is the most popular online resource for web standards, its content has a lot of serious flaws.

One such problem at W3Schools is variable scoping in JavaScript(w3schools page):

JavaScript has a global scope(global window object to be more precise), that is the place where all global variables go, usage of this must be minimized because in most pages there will probably be scripts from multiple sources, if everyone relies on the global scope, than sooner or later one script will get into conflict with another. The var keyword is not an optional decoration in JavaScript, if we leave out the var, then the global scope is assumed automatically. Here are some examples:

These functions declared global variables, therefore our local variable loses its original value:

something = 'first thing';
 
function foo() {
    something = 'foo';
}
function bar() {
    something = 'bar';
}
 
foo();
bar();
console.log(something); //'bar'

These functions declared local variables, no collisions have occurred here:

var something = 'first thing';
 
function foo() {
    var something = 'foo';
}
function bar() {
    var something = 'bar';
}
 
foo();
bar();
console.log(something); //'first thing'

W3Schools states the following too:

If you redeclare a JavaScript variable, it will not lose its original value.

While it may not cause an error now it is certainly not a good practice and could lead to confusion and maybe runtime errors in future versions of ECMA Script(JavaScript).

There are also other important facts about the var keyword that are not mentioned in W3Schools:

var is function scoped and not block scoped:

function test() {
    if (true) {
         var test = 3;
    }
}

works just like:

function test() {
    var test;
    if (true) {
         test = 3;
    }
}

Either way you will be able to access the variable test after the block. A better example might be:

for (var i=0;i<10;i++) {
}
console.log(i); //10

The best practice to avoid confusion is to begin each function with a single var declaration and declare all variables in that single var declaration. JSLint can help you with that. And learning more about JavaScript is as easy as watching a couple of videos I outlined in one of my previous posts.

Update:
the best comment this article/issue received so far: http://www.reddit.com/r/web_design/comments/fa9hp/what_they_dont_teach_you_in_w3school_javascript/c1ejet7

Update 2: made the w3schools link weaker.

Update 3: added rel=”nofollow” to w3schools links.

Avoiding SQL

January 16th, 2011

I have been writing dynamic database-backed web applications since 2006, still whenever I fire up my IDE, I can’t help notice that the SQL in my code doesn’t feel natural, my IDE can’t parse it, because in essence, it’s a string that gets created on runtime. SQL itself can be pretty counter intuitive, it has poor support for complex data structures, one of it’s main weaknesses is that(to my knowledge) it can’t return nested structures. In terms of clarity, SQL doesn’t scale well, long SQL strings are really hard to understand.

In real life we have complex and nested data and we need to make our code as clear as possible. A common practice(MVC) is to put all the SQL into data access objects and use it’s API instead of raw SQL. I did just that I had most of my SQL in objects, what I found is that I kept repeating code and kept doing the same thing with every new data access object I made, but at least I always knew the purpose of the SQL queries, because they were encapsulated.

One day I kept hearing about NoSQL databases, they looked to offer something better but I ignored them because most hosting providers don’t support them. A while ago however I heard about object relational mappings(ORM), libraries which provide a native API on top of SQL. This sounded just like what I needed, something that could help eliminate the duplication I previously had with my data access objects.

I searched for an ORM written for PHP and I found Flourish ORM, after finding it I realized that this is what I needed all along. I can create a basic ActiveRecord in 3-4 lines of code, the only thing I need to specify is the database it maps to, the ORM layer reads the schema of the database and gives me dynamic methods that I can use instead of SQL.

//this is how we initialize
class User extends fActiveRecord
{
}
fORM::mapClassToTable('User', 'user');
//this is what we get
$user = new User();
$user->setName('Test user');
$user->setPassword('123456');
$user->store();

That’s it, I get similar methods for the rest of the database operations, one of the main benefits is that I no longer have to worry about string concatenation. I can override these methods at any time using standard OOP techniques. Of course this does not mean that I will never write SQL again, but I will write and maintain a lot less that I was used to. Another big advantage is that there is a standard API for data handling, if someone takes over my code, I could simply point to the Flourish documentation.

Avoiding the frustration of web designing as much as possible

June 19th, 2010

Every web designer and developer knows that the web is full of mess and it can be very challenging to create beautiful designs and advanced user interfaces. We all have been there, we all have done that. Web browsers follow their own path, CSS is terrible and counter intuitive for layouts. I wrote this article for both web designers and web developers, I did my best to avoid getting into deep coding.

So the question is: is there a way out of this madness? is there a way we can stop worrying more about compatibility than about our actual product?

It turns out there is a way, there is a way to get rid of most of the annoyances, so here are my tips for you to stay alive:

  1. Browser defaults are evil. Neutralize them! The YUI(Yahoo User Interface) Reset and YUI Fonts library can help you out here, you just include two CSS-es, and you can say bye bye to browser defaults. This eliminates the need to constantly monitor your design in multiply browser to check for conflicting defaults.
  2. CSS is counter intuitive for layouts, and is affected by a lot of browser quirks. You need to use a CSS library for layouts so you don’t have to worry about this. YUI Grids can help you out with this, it can really make building the skeleton of your website painless, also it is very much mobile compatible, which saves you work on mobile devices.
  3. Use a doctype that brings the best behavior out of most browsers, you don’t want your page to render in quirks mode.

This may seem to be easier said then done, but it’s actually easy to do too. There is a secret cheat code for the easier way out, type “yui grids builder” in Google search, and click “I’m feeling lucky”. I you perform this action correctly you are presented with this tool, which enables you to simply create a skeleton for your site and click “Show code” when you are done. You get a very good starting point for free, you get a layout, that is cross-browser. It is much easier to create a design based if you have this starting point.

Mobile web libraries – Sencha Touch

June 19th, 2010

When I thought I was through examining the most appealing mobile web libraries, the news came in that the newly (re)formed Sencha has put out a new one called Sencha Touch. Despite being something really new, it provides the best support for iOS(iPhone,iPod,iPad) and Android, in fact it only supports these:

Our initial beta is compatible with iOS and Android, which together represent over 90% of current US mobile traffic.

I neither agree nor disagree with this statement, though I agree that most mobile web market share does in fact come from iOS + Android. Typically this framework is aimed at developers who want to support these, and developers who want to support new technology. Sencha Touch heavily utilizes Webkit, CSS3 and HTML5, it doesn’t seem to be forgiving lesser user agents, this is what seems to differentiate it from jQTouch, despite the fact that Sencha claims to be: Ext JS + jQTouch + Raphaël. They however mentioned that they plan to support other forward thinking devices.

Sencha Touch seems to be the only mobile web framework so far that provides touch support like: tap, double tap, swipe, tap and hold, pinch, and rotate. The problem I found with this is that there is no compatibility chart for Sencha Touch and few of it’s examples actually work on my Android 1.6 phone, which questions Sencha Touch’s Android support.

A weird fact is that Sencha Touch’s API is really Ext JS(see source), even the source codes use the Ext global object. The release I downloaded is labelled 0.90 beta, which discourages me to use it for actual products, because it will probably get a refactoring by the time it reaches 1.0, in fact I wouldn’t have called this beta in the first place.

My final verdict is to use this framework only if it makes sense, it is a superior alternative to writing native applications(because we don’t have to do platform specific builds), but it’s not as compatible as one would expect, which can be a problem because of the Android platform fragmentation. What I would like to see in the future is some jQuery integration(because of jQTouch) and a more forgiving interface, possibly a way to know the browser’s features, my biggest need is a good way to detect drag n drop support.

Update 2010-06-24:

A lot of HTC(and probably others) Android phones will get an upgrade to Android 2.1, which will (hopefully) render some of my above arguments irrelevant. Also worth noting that Sencha Touch is about being future-ready, which in the current circumstances is more reasonable than the opposite.

http://androidcommunity.com/htc-tattoo-getting-2-1-20100311/

http://phandroid.com/2010/03/11/htc-tattoo-getting-android-2-1/

Mobile web libraries – jQTouch

June 17th, 2010

The state of mobile web development is quite good nowadays, we have WPtouch, we have iUI, but there is always room for other libraries. jQTouch is yet another mobile web UI library. It is based on jQuery, and it is not like iUI, it has taken a different approach, it tries to keep the same convention of letting the user create simple interfaces via HTML, but at the same time it leverages jQuery.

This project not only uses jQuery but extends it, part of jQTouch is a jQuery plugin which has huge benefits: theoretically I can take the jQTouch plugin and use only some parts of it, even create yet another mobile web UI. This is the part where jQTouch differentiates itself from iUI, I think it is better than iUI in this perspective, it gives coders more possibilities.

jQTouch also had descent documentation.

Since I’m comparing jQTouch and iUI, I must also note that iUI seems to have more features and seems to be more mature. A thing they have in common is neither of them works in Opera Mini, but I feel it’s more Opera Mini’s fault.

Since I’m a coder, who has much love for jQuery, I certainly prefer jQTouch for a bigger project, it looks to be more well crafted from a coder perspective, but if I were to do a simple site and fast, I would probably choose iUI, because it has more to offer out of the box.

To close this I encourage anyone to try out both and decide which one has the most features that are needed.

Mobile web libraries – iUI

June 16th, 2010

Mobile computing is evolving, we either catch up with it or remain out of this growing market. Mobile devices usually have small screens which most of the time makes it impossible to create a one size fits all design. I already wrote about WPtouch, and how simple it is to make a WordPress blog to be mobile-friendly. But we need something that can help us out in other scenarios, we don’t want to start developing for mobiles from scratch, because it is both hard and expensive(actually hard=n*expensive) so we want to avoid it.

I discovered a library called iUI, it’s a web framework for creating interactive iPhone and iPod compatible web UIs from simple html. It has a simple and intuitive HTML API, that most web developers can pick up instantly. The written HTML is utilized by a JavaScript/CSS engine, that turns it into an iPhone web application.

This is how a typical(partial) iUI markup looks like:

<div class="toolbar">
 
        <a id="backButton" class="button" href="#"></a>
        <a class="button" href="#searchForm">Search</a></div>
<ul id="home" title="Music">
	<li><a href="#artists">Artists</a></li>
	<li><a href="#settings">Settings</a></li>
	<li><a href="stats.gtpl">Stats</a></li>
	<li><a href="#themes">Theme Switcher</a></li>
	<li><a href="#iui-cache-panel">HTML5 WebApp Cache</a></li>
	<li><a href="http://code.google.com/p/iui/" target="_self">About</a></li>
	<li>Nothing</li>
</ul>
<ul id="artists" title="Artists">
	<li class="group">B</li>
	<li><a href="#TheBeatles">The Beatles</a></li>
	<li><a href="#BelleSebastian">Belle &amp; Sebastian</a></li>
	<li class="group">C</li>
	<li><a href="#CrowdedHouse">Crowded House</a></li>
	<li class="group">J</li>
	<li><a href="#JennyLewis">Jenny Lewis</a></li>
	<li><a href="#JohnMayer">John Mayer</a></li>
	<li class="group">Z</li>
	<li><a href="#Zero7">Zero 7</a></li>
</ul>

Full working example found here: http://iui.googlecode.com/hg/web-app/samples/music/music.html#_home

The concept is simple, there are pages, which can be ULs or DIVs, which contain elements, mostly A tags, which link to other pages by referring to them via link hash, for example: <a href=”#foo”>Go to foo page</a>. There is also support for iPhone-like form controls and AJAX form submissions and of course themes.

This video(direct download) explains most of the features and usages better than I can, and there is always the wiki and the source documentation.

This project is developing nice in general, however last time I checked the code it wasn’t too pretty it was really ugly at some parts and a flaw is that this only works in modern browsers and does not work under Opera Mobile, because it uses JavaScript timing functions which Opera Mobile does not support.

So if either clean code or Opera support is a requirement then iUI may not be an option, otherwise it is definably worth considering. Note that the project is relatively young so I think it will improve in the future, a new feature it is bringing is iPad support.

Mobile web libraries – WPtouch

June 15th, 2010

If you have a WordPress blog(like this one here) and want it to function optimally under iPhones, iPads and Android devices and don’t want to code it yourself , this is the solution for you. WPtouch is a plugin that detects a set of mobile browsers, and creates an alternative mobile UI that accommodates to the small screen size and looks a lot like a native mobile application. Having this plugin installed is a huge difference maker, mobile users won’t have two scrollbars and won’t have to use zooming to read articles.

This is a commercial product, but it is actually not that significant, the pricing is quite reasonable, compared to the cost it would take to develop this from scratch. The reason I say that the pricing is not significant is the fact that this plugin is licensed under GPLv3, which makes this a very favorable deal.

That’s why WPtouch Pro is fully compatible with WordPress’ GPL license. That means once you buy it you’re free to use the purchased software as you see fit. Support and automatic upgrades from us are tied to your purchased license, but you’re free to use the original software in whatever way it suits you.

For a lot of people the free version should be enough. The free version also allows potential customers to experience it before grabbing hold of the credit card. The pro versions give a lot of reason for purchase too, definably worth considering.

I don’t want to outline the and compare all the features of WPtouch, it is presented perfectly at it’s site. To sum this all up, if you want mobile accessibility for your WordPress, this plugin is definably worth your time.

Homepage: http://www.bravenewcode.com/products/wptouch-pro/

Disclaimer: I am not affiliated with BraveNewCode Inc., the opinions expressed are solely my own. I just like and use the product.

Experimental and partial mobile support

May 22nd, 2010

Just recently I introduced mobile support with WPTouch, a wordpress plugin that, transforms the blog if it detects an Android, Black Berry or iPhone browser. This is not what I would like to experiment with in the future, I want to try the one size fits all method, but less is always better than nothing. It’s nice now that I get a mobile layout if I view my blog with my mobile phone.

I encourage others to try this out, this is really a fine tool!

Node.js

May 22nd, 2010

I just watched Ryan Dahl — Introduction to NodeJS on YUI Theater and I am very exited, it surprised me, it sounds really crazy without the details. Today’s web servers mostly use threads or processes for each request they serve. The problem with this is the fact that threads and processes cost resources(CPU cycles and RAM), this is justified by the fact that most requests start and end very quickly, however if we have a lot of concurrent requests things can really heat up. If a web server gets a lot of incoming requests at the same time it needs to have a lot of threads/processes running, which increase the RAM and CPU usage and decrease the response time. This is a grave problem if we have a high traffic site or a chat application which keeps a connection open for a very long time.

So the question may be asked: why do we use threads anyway?

The answer: We could use a nice event loop but the problem is that we have a lot of function calls that block the execution like this one:

result = db.query(“SELECT * FROM foo”);

This line of code will pause our current thread until we get a answer from the database, and it takes long(socket connections etc.). In an event loop we can’t afford to have these instructions pause our loop, that means that we would basically have our clients wait in line.

The resolution: Make them stop blocking us!

So If we were to turn these blocking routines into non-blocking routines we would live in a better world.

Let’s have a look at JavaScript. The browser is one threaded still we are fine with it, we don’t need no threads there: why is that?

It’s because we have instructions like these:

//do something time consuming
$.getJSON('ajax/some.php', function(data) {
  //wake me up when you are done!
  //do something with the result
});

So we have asynchronous, non-blocking routines in JavaScript, that’s why we don’t care about threads.

If this is better, why aren’t people using this instead of threads?

According to Ryan Dahl, this is mostly because of bad habits, it would be somewhat harder to teach non-blocking IO and basically most of the tools we have now have only blocking IO. I feel that the main reason is probably that most languages don’t make writing callbacks easy and simple, unlike JavaScript.

Solution: let’s write a one threaded web server with JavaScript.

This is what Ryan Dahl and others are doing, this is what Node.js is all about. They abstract the ugliness of the underlying libraries and make IO routines non-blocking.

One may note: JavaScript is not the fastest language…

Answer: V8(Chrome’s JavaScript engine) all the way!

Node.js is far from ready for prime time, but it is definably usable in some cases where we would really need it. I recommend those interested in this to watch the video presentation, and to go to http://nodejs.org/, download Node.js(it’s free, MIT license) and give it a try. I successfully compiled it under Debian unstable and now experimenting with it.

More fonts for the web!

May 20th, 2010

The forces of Google have struck again! This time Google is providing us a font directory containing free/ready to use fonts to make web typography more interesting. All major browsers support font embedding.

Ever since Firefox started supporting custom fonts, it’s not a problem to make browsers use them, the problem however is that most fonts have some license that is not friendly towards doing this. Since we now have directory devoted to freely distributable fonts, we can finally start impressing people with very nice looking fonts, without worrying that they won’t have it.

Another nice thing is that we don’t even need to know the “black magic” for making use of these fonts, Google’s directory makes it very easy to use these fonts intermediately without problems, they offer code snippets for doing so. I tried one out myself, to see it working, and of course it worked, even in IE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE HTML>
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href='http://fonts.googleapis.com/css?family=Tangerine' rel='stylesheet' type='text/css'>
    <style>
        h1 { font-family: 'Tangerine', arial, serif; }
    </style>
  </head>
  <body>
      <h1>This is a test</h1>
  </body>
</html>