The title says it all, but I will provide more clarification:
After seeing many samples of javascript where all variables are declared as type var
, and seeing support for other datatypes, why aren't variables of a specific datatype declared as such? Meaning, why isn't this:
string hello = 'Hello, World'
used instead of
var hello = 'Hello, World'
Looking at sites like OReilly Javascript shows that there are reserved words for other types. Again, why aren't they used? Wouldn't it make lines like this: typeof(variable)==='string';
no longer needed?
Quite simply, JavaScript variables do not have types. The values have types.
The language permits us to write code like this:
var foo = 42;
foo = 'the answer';
foo = function () {};
So it would be pointless to specify the type in a variable declaration, because the type is dictated by the variable's value. This fairly common in "dynamic" languages.