In JavaScript, adding 1, the string “2” and 3 gives the string “123”. Adding 1, 2 and the string “3” gives “33”. Subtracting 2 from the string “5” gives the number 3. In PHP, the string “10” is equal to the integer 10 when compared with two equals signs and not equal when compared with three. These look like trivia, but they all follow from one design decision: when an operation receives values of the wrong type, the language converts them instead of refusing. That conversion is called type coercion, and once you know the rules, the surprises become predictable.

Strong refusal versus helpful conversion

Languages differ in how they treat mismatched types. Python raises a TypeError if you add a string and an integer; you must convert explicitly. Java allows string concatenation with + but will not let you subtract a string from a number. JavaScript and PHP take the opposite view: they try to find some conversion that makes the operation meaningful. That makes quick scripts convenient and makes certain bugs silent.

JavaScript’s plus sign has two jobs

The + operator means numeric addition or string concatenation. The rule, slightly simplified: if either operand is a string after converting objects to primitives, concatenate; otherwise add numbers. Evaluation goes left to right, one pair at a time.

  • 1 + “2” is “12” (a string is involved, so concatenate). Then “12” + 3 is “123”.
  • 1 + 2 is 3 (two numbers). Then 3 + “3” is “33”.

Every other arithmetic operator (-, *, /) only means arithmetic, so JavaScript converts strings to numbers. “5” minus 2 is 3, and “5” times “2” is 10. A string that does not look like a number becomes NaN, which then spreads through every calculation it touches.

The real-world version of this bug is form input. Values from HTML inputs are always strings. A cart that adds a quantity field to an existing count without converting it will show 1 + “2” as 12 items. The fix is explicit conversion at the boundary, using Number or parseInt with a radix, and validating the result.

Loose and strict equality in JavaScript

JavaScript has two equality operators. Strict equality (===) compares type and value without conversion: “10” and 10 are different. Loose equality (==) converts first, following an algorithm in the language specification. Some results of that algorithm:

Comparison with ==ResultWhy
“” and 0trueEmpty string converts to the number 0
“0” and falsetrueBoth convert to the number 0
null and undefinedtrueSpecial rule: they equal each other and nothing else
null and 0falsenull is not converted to a number for ==
NaN and NaNfalseNaN is not equal to anything, including itself

Most style guides and linters (ESLint’s eqeqeq rule, for example) require ===. A common, deliberate exception is checking a value against null with ==, which catches both null and undefined in one test. TypeScript reduces the problem further by catching many type mismatches at compile time, though it cannot help with data that arrives at runtime from an API or a form.

PHP: same idea, different rules, and a version change

PHP also has == (loose, with type juggling) and === (identical: same type and same value). “10” == 10 is true because the numeric string is compared as a number. “10” === 10 is false because one is a string and the other an integer.

Comparing a non-numeric string with a number is where history matters. In PHP 7 and earlier, “abc” == 0 was true: the string was converted to a number, and a string with no leading digits became 0. PHP 8 changed this. Now, if the string is not numeric, the number is converted to a string and the two strings are compared, so “abc” == 0 is false. Code written for PHP 7 that relied, deliberately or by accident, on the old behaviour can change meaning after an upgrade, which is one reason PHP 8 migrations deserve proper testing.

Even in PHP 8, two numeric strings are compared as numbers. “1e3” == “1000” is true, because both are numeric and 1e3 is scientific notation for 1000. “10” == “10.0” is true as well.

When coercion becomes a security problem

That numeric-string rule produced a well-known class of PHP vulnerabilities sometimes called “magic hashes”. Hex-encoded hashes such as MD5 output occasionally take the form “0e” followed only by digits. PHP reads such a string as scientific notation for zero. Two different hashes of that form compare as equal with ==, because both are zero. A login check that compared a computed hash to a stored one with loose equality could therefore accept a wrong password whose hash happened to have that shape.

The lessons generalise. Compare secrets with strict, constant-time functions designed for the purpose (PHP’s hash_equals and password_verify). Never compare security-relevant values with loose equality. And be wary of any API that accepts JSON, because an attacker can send a number or boolean where your code expected a string, and loose comparisons may then behave in ways you never tested.

Habits that avoid the whole category

  • Use strict equality by default in both languages, and turn on the linter rules that enforce it.
  • Convert and validate types once, at the edge where data enters (request parsing, form handling), so the rest of the code deals with known types.
  • In PHP, consider declare(strict_types=1) so scalar type declarations on functions are enforced rather than coerced.
  • When something prints a strange value, ask what type each operand actually had at that moment. Logging with type information, not just the value, settles it quickly.

Coercion is not a flaw to be ashamed of; it made these languages easy to start with. It simply moves the burden of type discipline from the language to the programmer.

Written by the RP Strativa Team.

Leave a Reply

Trending