33

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?

CBredlow
  • 2,790
  • 2
  • 28
  • 47
  • 8
    Javascript is an untyped language. http://stackoverflow.com/questions/964910/is-javascript-an-untyped-language – Jonas G. Drange Jan 07 '13 at 19:33
  • 2
    @JonasG.Drange ECMAScript is a [*dynamically* typed](http://c2.com/cgi/wiki?DynamicTyping) language. (Values still have types and thus can't be *un*-typed language.) –  Jan 07 '13 at 19:42
  • 1
    @pst read the linked answer carefully. There is a deliberate abuse of the language "untyped" to be a shorthand for "no static types." I disagree with that abuse, but that's another issue. – Matt Ball Jan 07 '13 at 19:44

1 Answers1

68

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.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710