Meanwhile: Javascript

25 May 2017 in Javascript, Fun

I can't resist on this (kudos to https://twitter.com/lukaseder/status/867080556470730752):

> '5' - 3
2
> '5' + 3
'53'
> '5' - '4'
1
> '5' + + '5'
'55'
> 'foo' + + 'foo'
'fooNaN'
> '5' + - '2'
'5-2'
> '5' + - + - - + - - + + - + - + - + - - - '-2'
'52'
> var x = 3;
undefined
> '5' + x - x
50
> '5' - x + x
5

This is called type coersion (in javascript) and can bite you hard if you aren't aware of this.

What about PHP (the 5.6 version):

php > echo '5' - 3;
2
php > echo '5' + 3;
8
php > echo '5' - '4';
1
php > echo '5' + + '5';
10
php > echo 'foo' + + 'foo';
0
php > echo '5' + - '2';
3
php > echo '5' + - + - - + - - + + - + - + - + - - - '-2';
7
php > $x = 3;
php > echo '5' + $x - $x;
5
php > echo '5' - $x + $x;
5

And Python:

>>> '5' - 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'

OK, got the point, no need to continue...