JAVASCRIPT

All Languages C CPP JAVA HTML CSS JAVASCRIPT PYTHON

Variables & Its Types in JavaScript

You oftentimes read that JavaScript is an untyped language. That statement implies that the language simply doesn't have types. Quite the contrary is true! JavaScript is full types.

In JavaScript, variables don't have types, but values do.

It is, however, correct to say that JavaScript is not a statically typed language. This means that when you declare a variable, there's no way to specify its type to restrict the set of values that can be assigned to it:

let foo = "bar";
// `foo` now holds the string value "bar"

Furthermore, just because a variable initially contained a string value doesn't mean that it can (from that point on) only contain string values. Values of different types can be freely assigned:

let foo = "bar";
// `foo` now holds the value "bar" of type string

foo = false;
// `foo` now holds the value false of type boolean

foo = 1337;
// `foo` now holds the value 1337 of type number

The above code is perfectly valid because in JavaScript, variables don't have types. Variables can hold arbitrary values, and these values have types. Think of variables as labeled boxes whose contents can change over time.

Built-In Types and the typeof Operator

Each value in JavaScript has one of these seven built-in types:

You can inquire about the type of a given value by using the typeof operator:

let foo = "bar";
typeof foo; // "string"

foo = false;
typeof foo; // "boolean"

foo = 1337;
typeof foo; // "number"

Although it might look like typeof returns the type of the variable foo, it returns the type of the value currently stored within the variable. Again, in JavaScript it's not variables that have types, but values.

The string returned by the typeof operator is always one of these seven strings:

Notice that there's a (possibly surprising) mismatch between the seven built-in types and these seven strings, e.g. typeof null === "object".

Statically Typing Variables with TypeScript

If you'd like to be able to restrict your variables to only hold values of a certain type, you can write your application in TypeScript is a superset of JavaScript that adds optional static typing to the language. The TypeScript compiler will then type-check your program and complain if there's a type mismatch:

let foo: string = "bar";
// `foo` now holds the value "bar" of type string

foo = false;
// Error: Type 'boolean' is not assignable to type 'string'

In TypeScript, variables do have a static type. However, the entire static type system is a purely compile-time artifact. Once your TypeScript code has been transpiled to plain JavaScript, the notion of static types is gone and nothing stops you from assigning values of a different type to a JavaScript variable.