Search code examples
loose-typing

How does a loosely typed language know how to handle different data types?


I was working on a simple task yesterday, just needed to sum the values in a handful of dropdown menus to display in a textbox via Javascript. Unexpectedly, it was just building a string so instead of giving me the value 4 it gave me "1111". I understand what was happening; but I don't understand how.

With a loosely typed language like Javascript or PHP, how does the computer "know" what type to treat something as? If I just type everything as a var, how does it differentiate a string from an int from an object?


Solution

  • What the + operator will do in Javascript is determined at runtime, when both actual arguments (and their types) are known.

    If the runtime sees that one of the arguments is a string, it will do string concatenation. Otherwise it will do numeric addition (if necessary coercing the arguments into numbers).

    This logic is coded into the implementation of the + operator (or any other function like it). If you looked at it, you would see if typeof(a) === 'string' statements (or something very similar) in there.

    If I just type everything as a var

    Well, you don't type it at all. The variable has no type, but any actual value that ends up in that variable has a type, and code can inspect that.