JavaScript Pitfalls for PHP-Developers

A couple of years ago, PHP developers only had to have strong knowledge in the language itself and experience in some PHP frameworks and libraries, additionally skills in MySQL were expected.
If we take a look at our current job advertisement, these knowledge is still important, but also skills in JavaScript are asked and strongly desired. If you wonder why JavaScript is so popular at these times, my answer is quite simple: The browser is no longer a stupid instrument to view some static websites on the internet- the browser turned into an (Web-) Application Platform that provides more content then plain text. This results in more and more complex sites and therefore in much more source code. One of the reasons for this progress is AJAX, which is the art of exchanging data with a server, and updating only parts of a website (with JavaScript). Therefore JavaScript is the big winner on this evaluation, because it is available on nearly every browser, needs no plug in or any additional software and it is easy to learn. In the early days of the internet we used JavaScript to create some lousy effects or did some simple checks for any input fields. These days are gone, it is not unusual to have more JavaScript code than PHP code in large projects. Coding with JavaScript is not the same as coding with PHP, that´s the reason why I will write down some typical pitfalls for a PHP developer whose coding JavaScript.

Data types

There are two major data types in JavaScript, the primitive one (Boolean, String, Number, …) and Object (Array, Function). To check the data type the keyword typeof keyword might help you. But be aware! Objects are the fundamental units of JavaScript and virtually everything in JavaScript is an object and takes advantage of that fact. Even the primitive data types have so called “primitive object wrapper” and there´s great potential for wrong usage of the typeof keyword and checking the data type. Here is a small overview what you will get if you use the typeof keyword with several variables:

Variable

typeof Variable

{company: ‚Mayflower‘}

object“

[‚Mayflower‘,’PHP‘]

object“

function(){}

function”

a simple String”

string”

123456789

number”

true

boolean”

new String(“Mayflower”)

object”

new Employe( )

object”

You can see, you will not always get what you expect. Therefore it´s not always a good choice to check the data type with typeof. A better approach is to use the constructor property to identify the data type of a variable.


var myArr = [ ];
if (myArr.constructor === Array) {console.log(“yes, I am an Array!”)}

The downside of this approach is the needed comparison to a known data type. If you create your Array with the new operator, you can get the data type with the prototype property, like this:


var myArr = new Array();
console.log(myArr.prototype); // Array()

Array !== Array

In the PHP world an array is a wildly used data type and we are differ between the zero indexed, comma separated array and hash tables of key-value pairs, better known as associative arrays. In JavaScript an Array is just a simple zero indexed list of values- nothing more. There is no associative array in JavaScript. There is no trailing comma support for IE (causes an error)


var myArr = ['Mayflower','PHP','JavaScript'];

In JavaScript is something like an associative array, but this has nothing to do with the Array data type. The JavaScript world calls this an object literal and is a collection of key value pairs.


var obLiteral = {company: “Mayflower”, offices: ['München','Würzburg'] };

By the way, you are right if you say “the syntax looks like for a JSON string”. The syntax for an object literal and a JSON string are pretty similar with one main difference: For a JSON string the property names need to be wrapped in quotes to be valid. For object literals the quotes are only required if the property name have spaces or any other not valid identifiers.

for (… in … ) !== foreach

When you are working with Arrays the you surely know the foreach construct to iterate over the array. Against the common opinion, the for (… in … ) construct is not the JavaScript equivalent of foreach and it is not the best way to iterate over an array in JavaScript.

DO: Use the for (…) loop for iterations over array objects
Every JavaScript array provides a length property, so it is the best practice for iterating over a JavaScript using a simple for construct.

DON´T: Use the for (… in …) loop for iterations over array objects
It is not impossible to use the for (…. in … ) loop with an array (you remember, arrays are objects, too), but it can lead to some ugly errors because JavaScript is a powerful language and you can add functionality and properties to nearly every existing object (this is called augmentation). If you iterate over an augmented array object you will not get only the elements of the array, you will even get the augmented functionality and this may occur in an error.

The thing with the semicolon

Have you ever heard about “line termination with semicolon insertion”? JavaScript provides a mechanism that adds a semicolon to the end of a line if you forget it. At a first look this may be helpful but it can be the reason for endless debugging sessions. Imagine the following situation:


function user(){

return


{

company: “Mayflower”,

business: “PHP Development”

}

}

The user function will run without any error and will return a valid value (Ok, it´s undefined but it´s a valid return value). It´s not the desired object literal because the semicolon insertion terminates the function after the return.

I´m sure there are a lots of more pitfalls for PHP Developers, if you are interested in real crazy JavaScript I recommend a visit at http://wtfjs.com/.

PHP-Unconference 2009

Am vergangenen Wochenende (12.09./13.09.09) fand die dritte PHP-Unconference in Hamburg statt. Organisiert wurde die Unconference von der Hamburger PHP-User-Group im Geomatikum. An dieser Stelle möchte ich gleich dem Team danken, die Organisation war wirklich spitze, es fehlte an nichts.

Dies war meine erste Unconference und im Vorfeld war ich etwas skeptisch, denn es gab keine Liste mit Speakern und eingereichte Vorträge oder einen festen Zeitplan, lediglich auf der Webseite wurden Vorschläge und Interessen der Besucher gesammelt. Aus der Sammlung dieser Vorschläge wurde dann an beiden Tagen abgestimmt, welche Vorträge gehört werden wollen. Jedem Besucher standen dazu am Samstag und Sonntag jeweils drei Stimmen zur Verfügung, die mittels Aufkleber an die Vorträge vergeben werden konnten. An den Ergebnissen dieses Wahlverfahrens konnte man meiner Meinung nach auch erkennen, was die PHP-Community bewegt und vielleicht auch, in welche Richtung sich die Programmierung mit PHP in nächster Zeit entwickeln wird. Das schließe ich daraus, weil Vorträge wie „PHP Enterprise-Skalierbarkeit und Sicherheit“, „QA in Zukunft“, „Domain Driven Design“, „Test Driven Design“, „Scrum“, „Softwaremetriken“, „MVC Design Pattern“ und „Unit testing“ bestens besucht waren und die Diskussionen dazu oft über den Vortrag hinaus andauerten.

In denen von mir besuchten Vorträgen gefiel mir die Diskussionen zum Model View Controller Design Pattern mit Stefan Priebsch und den anwesenden Zuhörern am besten. Weit über den geplanten Zeitrahmen hinaus wurde besprochen, wie „Best Practises“ in der Umsetzung des Entwurfsmusters mit dem Zend Framework aussehen könnten. Aber auch in den anderen Vorträgen wurde eifrig diskutiert. Bei „PHP-Enterprise- Skalierbarkeit und Sicherheit“ wurde von Kris Köhntopp an Hand von vielen Beispielen gezeigt, wie überhaupt eine „Enterprise-Umgebung“ aussieht und welche Anforderungen dabei nicht nur an den Quellcode sondern auch an die einzelnen Softwareentwicklungsprozesse entstehen. Lars Jankowfsky und Johann-Peter Hartmann trugen mit ihren Erfahrungen zur Diskussion bei und belegten die Aussagen von Kris Köhntopp mit Beispielen.

Ein völliger Kontrast bildet der Vortrag „Rich Internet Applications mit Adobe Flex und Zend Framework“. Dabei stand nicht die Entwicklung mit PHP und dem Zend Framework in Mittelpunkt, sondern wurde gezeigt, wie mit PHP eine Schnittstelle zu Actionscript geschaffen werden kann und somit das Flex- Framework genutzt werden kann. Speaker Jörg Ohnheiser argumentierte den Einsatz von Flex mit den reichhaltigen GUI-Elementen die zur Verfügung stehen und der dadurch besseren Usabillity. Ich konnte nicht überzeugt werden und vertrete auch weiterhin den Standpunkt, dass auch mit Javascript- Toolkits, die solche GUI-Elemente enthalten, die Usabillity von Webanwendungen verbessert werden kann- unabhängig von einem einem Browser-Plugin (wie dies der Fall ist bei Flex- Anwendungen). Einzig bei Video- und Audio-Inhalten macht der Einsatz von Flex für mich Sinn.

Das Fazit der Unconference fällt natürlich sehr positiv aus, ich komme nächstes Jahr sicher wieder! Neben den guten Vorträgen stand vor allem das Netzwerken in den Kaffeepausen im Vordergrund und es entwickelten sich viele sehr gute Gespräche und ein reger Meinungsaustausch. Als Location war Hamburg natürlich auch optimal, neben der Unconference bot die Hansestadt genügend Möglichkeiten sich den Abend zu vertreiben, so zog auch der „PHP Mob“ durch verschiedene Bars und Kneipen.

Die folgenden Bilder wurden uns freundlicherweise von Ulf Wendel zur Verfügung gestellt, danke Ulf :-)