Tell JavaScript's Types Apart

Your desk now throws errors the volunteers’ script can name. The next trouble arrives from the other side of the tracker: the values volunteers type at the terminal. When someone types Priya’s age, does the tracker get the number 9 or the text "9"? Before you convert anything, you need a way to tell what kind of value you’re holding.

In this lesson, you’ll sort every JavaScript value into one of eight types and predict what typeof reports for each, including the surprises. Two of those types are new to you, and you’ll start with symbols by tagging a toy without the tag getting in the way.

Tag a Toy With a Symbol

The volunteers want to mark toys that need a wash after a busy Saturday. The mark belongs on the toy’s record, but it mustn’t collide with a property such as name, now or later, and it mustn’t end up in toys.json when the tracker saves the records with JSON.stringify().

A symbol is a primitive value made for exactly this job. Each call to Symbol() makes a new value that’s equal to no other, so a property keyed by it can’t clash with any other key. The text you pass in, such as "tag", is its description. It’s a label for logs and debugging, and you can’t use it to look the symbol up.

You keep the symbol in a variable and read the property with that variable inside square brackets, as in train[TAG]. Writing train.TAG or train["TAG"] asks for an ordinary key spelled TAG, which the record doesn’t have. Save this script as tag-train.js:

Language: JavaScript Filename: tag-train.js
const TAG = Symbol("tag");
const train = { id: "T01", name: "Wooden train set" };
train[TAG] = "needs a wash";

console.log("Read:", train[TAG], train.TAG, train["TAG"]);
console.log("Same?", TAG === Symbol("tag"));
console.log("Keys:", Object.keys(train));
console.log("JSON:", JSON.stringify(train));
const copy = { ...train };
console.log("Copy:", copy[TAG]);
console.log("Symbols:", Object.getOwnPropertySymbols(train));
console.log("Logged:", train);

Before you run it, predict which of these five show the tag: Object.keys(), JSON.stringify(), the spread copy, Object.getOwnPropertySymbols(), and logging the whole record.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.