I have been programming in PHP much longer than I’ve been programming in Javascript. As a matter of fact, I really haven’t programmed much in Javascript at all. I’ve copied and pasted a lot of snippets from the web and I’ve tweaked things and made a few small functions, but I’ve never done much on my own. Usually, I could get by with doing most things in PHP. (By the way, that’s about to change. I’ve become very fascinated with Javascript and jQuery lately, so I’m going to dive in and master them!)

When I was in college, my professors always taught us that programming is programming and the only real difference between languages is the syntax. If you can program in one language, you can program in another as long as you learn the new syntax. The concepts in each language are basically the same. For instance, a loop is a loop and a conditional statement is a conditional statement no matter what the language.

In my 27+ years as a programmer, I’ve found that to pretty much be true. But, sometimes syntax can be a killer and cause some real headaches. Switching from PHP to Javascript sometimes bites me when it comes to syntax.

Yesterday, I was just trying to add two numbers in Javascript. In PHP, I could do it like this and it would give me what I expected – 30:

$numberA = '10';
$numberB = '20';
$total = $numberA + $numberB;
echo $total;

But, when I tried this in Javascript, I got something unexected – 1020:

numberA = '10'
numberB = '20'
total = numberA + numberB

Now, I have to say, my real life problem was a little more complex and my numbers were coming from another source so I had no control over whether they had been declared as strings or numbers. All I knew was that I needed to take variable A and add it to variable B and every language I’ve ever used used the ‘+’ for addition. Of course, I immediately figured out what was going on because I knew that the ‘+’ is also the way Javascript does string concatenation. I just had to figure out how to make the strings into numbers. Thank goodness for Google 🙂

To fix the problem, I just had to type the variables as Number’s like this:

numberA = '10'
numberB = '20'
total = Number(numberA) + Number(numberB)

Worked like a charm! I got my 30 instead of 1020!

Maybe this will help some other PHP programmer that is scratching their head from the switch to Javascript.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top