JS/PHP string concatenation mistype
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
This entry was posted on Thursday, October 25th, 2007 and is filed under JavaScript, php. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

October 31st, 2007 at 12:23 pm
[...] “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. [...]
November 1st, 2007 at 8:27 am
[...] 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. [...]
May 1st, 2009 at 10:02 am
[...] This post was Twitted by thefinley – Real-url.org [...]