Stoyan Stefanov

5 Surprises for PHP Developers Coming to JavaScript

Unique features concealed within familiar syntax

PHP programmers often see the familiar C-like syntax of JavaScript and think it’s all flowers and roses. And while trivialities like loops and conditions are pretty much equivalent in both languages, things get very weird very quickly. Let’s take a look at the top 5 marvels JavaScript has to offer to the unsuspecting PHP veteran.

1. Functions are objects

Consider a function:

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

It looks familiar, the only apparent difference being the missing $ to denote variables. But it turns out there’s more than that. The function sum() is actually an object. That means it can have properties and methods.

Something like:

 sum.length; // 2

… may come as a surprise. In this case length property of the sum object gives you the number of arguments this function expects.

And you’re not limited by built-in properties; you can assign any properties you like to the sum object. For example you can have a cache property that stores the results of previous (potentially expensive) calculations.

And since you can refer to functions just as regular variables, that means your function can take other functions as arguments (callbacks) and can also return functions as return values.
Read more…