Learn TypeScript

Understanding the types in JavaScript

Understanding the types in JavaScript

Before we start to use the rich TypeScript type system, we will learn what types we have in JavaScript in this lesson.

Primitive types in JavaScript

JavaScript does have some basic primitive types, but what are they?

Click the link below to open an exercise where we will explore this question.

TypeScriptOpen exercise in CodeSandbox

The JavaScript code in the exercise outputs the types of four variables with various kinds of values. We’d hope for string, number, boolean, and date to be output … but is this the case?

  • Check the editors console and find out.

Nearly! JavaScript does have string, number, and boolean types, but there is no specific date type - instead, dates are of type object.

  • Let's experiment with some other variables. Copy, paste, and run the following code in the code editor above:
const count = BigInt(452947234234);
console.log("count", typeof count);
const address = null;
console.log("address", typeof address);
const phone = undefined;
console.log("phone", typeof phone);
const stars = Symbol("***");
console.log("stars", typeof stars);

The other primitive types that are available in JavaScript are bigint, null, undefined, and symbol.

Notice that the type of a null variable is object and not null as we would expect. This is a bug in JavaScript! This link gives more details of this bug.

For more information on the types in JavaScript, see this MDN page.

JavaScript is loosely typed

In loosely typed languages, you don't have to specify types of variables. JavaScript is loosely typed.

Examine the code below.

let amount = 10;
console.log("amount", typeof amount);
amount = "Eight";
console.log("amount", typeof amount);

The amount variable starts as a number but then is assigned to a string. So, we'd hope to get an error or maybe a warning, but do we? Copy, paste, and run the code into the code editor at the top of this page to find out.

We don't because JavaScript is loosely typed. There is nothing to prevent a variable from changing its type in JavaScript.

Summary

The take away from this lesson is that we only have a few useful types in JavaScript. JavaScript does not have the capability to declare that a variable is of a particular type. Instead, the type is inferred from the value it is assigned. There is no strict type checking in JavaScript either, which means that a variable can be changed to hold any value.

The lack of a rich type system with a type-checking process is what TypeScript brings to the table. We’ll learn how to use this type system in this course to make us more productive when developing apps.

In the next lesson, we will learn how to declare variables with types in TypeScript.

© 2023 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more