Published at
Updated at
Reading time
This post is part of my Today I learned series in which I share all my web development learnings.

Symbols are these relatively new types that were added to the language not too long ago. I have to say though that I'm not using them very often. Let's quickly recap with an MDN quote:

Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose.

And this is how they work (shamelessly copied from MDN):

const symbol1 = Symbol();
const symbol2 = Symbol(42);

console.log(typeof symbol1);
// expected output: "symbol"

// expected output: "Symbol(foo)"

Look like "normal" objects in JavaScript, right? Everything is an object in JavaScript anyways but today I discovered something odd. What happens when I want to set a new property on a symbol? (if that's a good thing to do is another question)

const a = Symbol(); = 'bar';
console.log(; // ?

The snippet above logs undefined to the console. This shows that it is not possible to set new properties on a symbol. The runtime is not throwing an error though.

The reason for that behavior is that symbols are primitives in JavaScript and primitives are immutable. This means the same functionality applies for the types Boolean, Null, Undefined, Number and String.

const a  = 123; = 'bar';
console.log(;    // undefined

const b = 'baz';
b.length = 2;
console.log(b.length); // 3

There are clearly not many use cases for setting a new or redefining a property on an e.g. Number (if there are any at all) but I didn't know that primitives are immutable in general and that's a nice nitty gritty detail of JavaScript to know.

Edited: As the reddit user pertheusual points out adding properties to primitives throws an exception in strict mode.

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 14 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles