To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Types in JavaScript

As mentioned previously in this tutorial, JavaScript is a weakly and loosely typed programming language (or dynamic language). This means that variables do not need to have a type assigned to them and the compiler (or the runtime) will assign a type to the variable based on the value.

But since it is also loosely typed, a variable can have it's type changed after it has been declared.

Types in JavaScript

JavaScript has six primitive types. A primitive type is a low level, non-object type. What this means is that the value has no methods. It is simply a value.

The six primitive types are:

  • String
  • Number
  • Boolean
  • Null
  • Undefined
  • Symbol

JavaScript also features one final type which will be covered later on in the tutorial. However, for completeness-sake it is known as the object type.

Take the following code sample:

JavaScript
var x = "Hello world"; //String
var x = 50; //Number
var x = true; //Boolean

In this example a variable x has been declared three times with three different values. Crucially however, the values all differ in type. The first value is a string and therefore the String type is assigned, the second value is a numeric value and therefore the Number type is assigned and the thrid value is a boolean value (true or false) and therefore has the Boolean type assigned to it.

Despite the difference in types, it is possible to assign a value of a different type to the same variable because the language is loosely typed.

Null

Null is a special type that means that the value of the variable is actually null too. A null value is a value that contains nothing, the value is empty or has no meaning. In JavaScript it can be assigned just like a normal value:

JavaScript
var x = null; //Null

Undefined

The Undefined type is another special type in JavaScript. The Undefined type simply stores a value that suggests the value has not been assigned a correct value.

JavaScript
var x = undefined; //Undefined

There is more on the undefined value on Wikipedia.

Provide feedback on this page
Comments are sent via email to me.