Evaluation of conditions is very important part programming. True is ture, false is false…
Or not? It might surprise you, but not all languages evaluate numbers, empty strings or empty arrays in the same way.
Let’s examine several technologies. Python, Ruby, PowerShell, NodeJS and PHP.
Here is small code written in Python:
def test(value): if value: print "True" else: print "False" test(0) test(1) test("") test([]) test({})
Here is similar code written in Ruby:
def test(value) if value print "True" else print "False" end end test(0) test(1) test("") test([]) test({})
Let’s compare it to PowerShell:
Function Test($value) { if ($value) { Write-Host "True" } else { Write-Host "False" } } Test(0) Test(1) Test("") Test(@()) Test(@{})
Same logic in JavaScript for NodeJS:
function test(value) { if (value) { console.log("True"); } else { console.log("False"); } } test(0); test(1); test(""); test([]); test({});
Code in PHP:
<?php function test($value) { if ($value) { echo "True"; } else { echo "False"; } } test(0); test(1); test(""); test(array()); test(array()); ?>
Results are little bit surprising:
Python | Ruby | PowerShell | NodeJS | PHP | |
0 | False | True | False | False | False |
1 | True | True | True | True | True |
“” | False | True | False | False | False |
[] | False | True | True | True | False |
{} | False | True | True | True | False |