Take the 2-minute tour ×

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?

share|improve this question

closed as not constructive by 0x499602D2, asgoth, Wesley Murch, evilone, Vohuman Jan 9 '13 at 16:50


Javascript is an untyped language. stackoverflow.com/questions/964910/… –  Jonas G. Drange Jan 7 '13 at 19:33
@JonasG.Drange ECMAScript is a dynamically typed language. (Values still have types and thus can't be un-typed language.) –  user166390 Jan 7 '13 at 19:42
@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 7 '13 at 19:44

2 Answers 2

up vote 17 down vote accepted

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.

share|improve this answer
So it's not possible to declare a type beforehand? –  CBredlow Jan 7 '13 at 19:39
That is correct. –  Matt Ball Jan 7 '13 at 19:41

JavaScript is a loosely-typed language, which by definition means you do not specify data-types. That being said you may find this post helpful: Typesafe Javascript

share|improve this answer
yeah, downvoter, what's the prob? –  Matanya Jan 7 '13 at 19:38
@Matanya Thanks for making me whole again :) –  Kevin Boucher Jan 7 '13 at 19:39
The language in this answer is imprecise. Who has defined "loosely-typed" to mean that data types are not specified? Even the more-commonly used terms ("strongly/weakly typed") are imprecise and ill-defined. (I didn't downvote) –  Matt Ball Jan 7 '13 at 19:41
See: stackoverflow.com/a/2351869/139010 –  Matt Ball Jan 7 '13 at 19:43
If they're ill-defined, than they can't be 'wrong'. Unworthy of the downvote IMHO especially considering the linked SO post. –  Kevin Boucher Jan 7 '13 at 19:46
