How to use typed variables in javascript?

Not possible in Javascript, but if you really need it, you should check TypeScript. It is a superset of Javascript that adds optional static typing. It also has class-based programming.


JavaScript variables are not typed.

JavaScript values are, though. The same variable can change (be assigned a new value), for example, from uninitialized to number to boolean to string (not that you'd want to do this!):

var x;       // undefined
x = 0;       // number
x = true;    // boolean
x = "hello"; // string

Javascript is dynamically typed, whereas other languages, C# and Java for example, are statically typed. This means that in Javascript variables can be reassigned to values of any type, and thus that you don't ever need to explicitly denote the type of variables or the return type of functions. If you saw code like this in a statically typed language

int x = 5;
x = "hello";

you would rightfully expect the compiler to start throwing up a big nasty TypeError. Javascript, on the other hand, will happily run this code even though the type changed.

var x = 5;
x = "hello";

Because variables can change types, the compiler can't know as much information about them. You should expect the tools for Javascript to be inferior to those of Java/C# as far as useful niceties like code completion go. Fewer mistakes will be caught at compile time and you will have to do more runtime debugging than you are probably used to.

That said, this also allows you to be more free with your variables and you can change types at will, which can often be convenient. You can write code like this if you want:

var x;               //typeof x === "undefined"
x = "Hello, world!"; //typeof x === "string"
x = 42;              //typeof x === "number"
x = false;           //typeof x === "boolean"
x = {};              //typeof x === "object"

Tags:

Javascript