Check out a free preview of the full Deep JavaScript Foundations, v3 course

The "const Q&A" Lesson is part of the full, Deep JavaScript Foundations, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle identifies situations where const can be useful.

Preview
Close

Transcript from the "const Q&A" Lesson

[00:00:00]
>> Speaker 1: If you use just const for strings, would that be a helpful way to?
>> Kyle Simpson: Yes, I only use the const keyword for primitive, immutable values. So that goes for strings, numbers, and booleans. And even then, I only use it when that thing is basically a semantic placeholder for where I would have just put the literal in one or a few places.

[00:00:20]
So I wouldn't just use it for every string just for the sake of using const. But if I had a string where I was gonna stick it somewhere, say for example an API URL, well, that's a perfect example. Your API URL's almost certainly not gonna change throughout the runtime of the program.

[00:00:37]
Assign it once at the top of that scope, call it customerApiUrl, and then use that const in the program. It gives semantic meaning to otherwise that string literal.
>> Speaker 1: And then with arrays and objects I usually just put deep freeze or freeze around it.
>> Kyle Simpson: So yes, I do like to use object.freeze, which is a shallow read-only lock of all the properties in an array or an object.

[00:01:07]
And that does sort of ostensively make it into an immutable value. Not really, since it's not deep, but it sort of does that purpose. Still, I won't say const x = object.freeze, because it pretends to the user as if const has something to do with the freezing, and it doesn't.

[00:01:26]
So I still would only use the const with one of the primitive immutable values.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now