37

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?

3
  • 8
    Javascript is an untyped language. stackoverflow.com/questions/964910/… Commented Jan 7, 2013 at 19:33
  • 2
    @JonasG.Drange ECMAScript is a dynamically typed language. (Values still have types and thus can't be un-typed language.) Commented Jan 7, 2013 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. Commented Jan 7, 2013 at 19:44

1 Answer 1

75

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.

Sign up to request clarification or add additional context in comments.

6 Comments

So it's not possible to declare a type beforehand?
what if i do var speed : float=10.00;
@AVIKDUTTA that's syntactically invalid JavaScript.
@AVIKDUTTA That is valid UnityScript (the version of JavaScript that the game engine Unity uses), but not JavaScript.
@MattBall it appears you are saying there is no way to always expect a variable value to always be a certain type in JavaScript? is that correct? Is this something that we "can" do with TypeScript?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.