JS/PHP string concatenation mistype

October 25th, 2007. Tagged: JavaScript, php

Another one from the "this is not a syntax error" department.

The front-end developer is a strange beast who has to jiggle to and fro and code in several languages literally at the same time - javascript, html, css, php or some other server side language, some SQL dialect... No wonder that sometimes we make silly mistakes like:

var $myarray;
var array = array();
$myarray = [];
foreach(var i in myarray)

Last night I just did a silly mistake like this. In JavaScript I used the PHP way of concatenating strings. Something like:

var user = 'Stoyan'; 
alert('hello ' . user);

This is obviously wrong, but the thing is that it's not a syntax error as one might expect. It alerts "undefined". Why is that?

Well, 'hello' is a string object. You can call methods and properties on it, like:

>>> 'hello'.toUpperCase()
"HELLO"
>>> 'hello'.length
5

And spaces don't matter...

>>> 'hello'     .   length
5
>>> 'hello'  . toUpperCase()
"HELLO"

So 'hello' . user is an attempt to access the "user" property of the string object 'hello'. This property doesn't exist, hence the "undefined" result.

Doing the opposite (using JavaScript-type concatenation in PHP) is also not an error:

$user = 'Stoyan';
echo 'Hello ' + $user; // prints 0

Tell your friends about this post: Facebook, Twitter, Google+

4 Responses

  1. [...] “Cross-over” developers out there (those that use PHP and Javascript on a regular basis) can sometimes get confused by little syntax things. Stoyan Stefanov got tripped up by just such an issue. The front-end developer is a strange beast who has to jiggle to and fro and code in several languages literally at the same time – javascript, html, css, php or some other server side language, some SQL dialect… No wonder that sometimes we make silly mistakes. [...]

  2. [...] JS/PHP string concatenation mistype Posted in November 1st, 2007 by admin in Javascript, PHP, Programming “Cross-over” developers out there (those that use PHP and Javascript on a regular basis) can sometimes get confused by little syntax things. Stoyan Stefanov got tripped up by just such an issue. [...]

  3. [...] This post was Twitted by thefinley – Real-url.org [...]

  4. My partner and i gotta favorite this page it seems like helpful beneficial

Leave a Reply