JavaScript Pitfalls for PHP-Developers

Avatar von Martin Ruprecht

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/.

Avatar von Martin Ruprecht

Kommentare

2 Antworten zu „JavaScript Pitfalls for PHP-Developers“

  1. Avatar von Nicolas BUI
    Nicolas BUI

    When using array or object litteral, some PHP developer are used to leave a last comma in array like :
    $foo = array( 45, 34, 45, );
    This also work with JavaScript, but it’s a bad practise as each browser will handle it differently (it will not work under IE, while it worked with firefox).

    Within object litteral, declaring a key with a reserved keyword will fail in IE, unless protecting with single/double quote.

    The biggest difficulty in javascript for php developpers is understanding the closure concept in javascript.

    Overall, I greatly recommand to any developper to use a good IDE like PhpStorm.
    If you write clean and separate JavaScript. I would rgreatly ecommand using JSLint to check syntax and style error (I have a ant script to do this work for me in my projects).

  2. Mighty ufesul. Make no mistake, I appreciate it.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert


Für das Handling unseres Newsletters nutzen wir den Dienst HubSpot. Mehr Informationen, insbesondere auch zu Deinem Widerrufsrecht, kannst Du jederzeit unserer Datenschutzerklärung entnehmen.