CodeNewbie Community 🌱

Discussion on: What's the difference between "let" and "const" in JavaScript?

Collapse
 
coderjoe82 profile image
Joseph Padgett • Edited

So when it comes to describing things like this, I like to try and make it analogous as possible.

Lets pretend that you have a treasure chest, and it's made with reinforced fiberglass. You know, really thick stuff so it's impossible to break easy with a rock! This treasure chest has no lock, and once you've put something inside of there and close it, it's in there forever. You can't change what's inside of it, but you can always look at it and see what it contains.

This treasure chest would represent const.

Lets pretend that you have a treasure chest designed exactly like the const one! Its only difference is it has a lock on it, and you have the key on you at all times! You, as pirate that controls all the way treasure is distributed on an island and to others, have complete control of the chest, what's in it, and what kind of things can go inside of it! Not only can you put whatever you want in there, but you can even decide it holds gold instead of gems, just by unlocking it and switching out its contents.

This treasure chest would represent let.

Now on to the more technical examples applied with the above analogies.

const String = 'yoooo'

String is 'yoooo' and cannot be anything but 'yoooo'

String = 'duuuuude'

String is already assigned and can't be reassigned! Same if you try to throw const in front of string

let String = 'yoooo'

Though you named it String, and makes it kind of silly to do so, lets "let" String be something else!

String = 8655309

String is now instead a totally random and not a two toned sequence of integers.

This is a very basic idea of these two things, but I hope it helps!

Collapse
 
lyqht profile image
Estee Tey

To add on to the great explanation by @coderjoe82 , you need to be mindful of the case where you assign an object as a const, say

const user = { name: "Bob" } 
Enter fullscreen mode Exit fullscreen mode

You can reassign the name property in this object with no problems.

user.name = "Alice" // will not throw error
Enter fullscreen mode Exit fullscreen mode

But if you reassign a different instance then it will throw an error

user = {name: "Carl"} //throw error
user = "Carl" // throw error
Enter fullscreen mode Exit fullscreen mode
Collapse
 
coderjoe82 profile image
Joseph Padgett • Edited

Yes to this!

I was trying to keep it basic so as not to confuse, because speaking in a newcomer terms, saying "You can't change WHAT type of value const has, if you have an array or object, you can change what's IN the type of value that it has" can be a little mind blowing until you're more comfortable, hah!