Https://www.codecademy.com/paths/create-a-back-end-app-with-javascript/tracks/bapi-javascript-fundamentals/modules/intro-to-javascript-for-apis/lessons/variables/exercises/const

What’s the difference between a variable var and a variable const?

From the Mozilla Developer Docs

var (Click for more…)

The var statement declares a variable, optionally initializing it to a value.

const (Click for more…)

Constants are block-scoped, much like variables defined using the let statement. The value of a constant can’t be changed through reassignment, and it can’t be redeclared.

2 Likes

OK, so what I understand is that the difference between them is having the possibility to reassign a value or not. But what’s the point of having a variable without an assigned value?

I think you might have misunderstood.

You can still “initialise” your const variables, the same way you can a var. You just can’t change them once they’re declared, they’re constant as the name implies.

Like so:

var my_variable_1 = 21;
console.log(my_variable_1);
>> 21

const my_constant_1 = 35;
console.log(my_constant_1);
>> 35

my_variable_1 = 99;
console.log(my_variable_1);
>> 99

my_constant_1 = 53;
>> TypeError: Assignment to constant variable.

Oh, I see. Thank you that helps a lot. What about the difference between let and var variables, then?

Someone else may correct me, as compared to some of the others here on the forum my JavaScript is not brilliant.

As I understand it, any variable you declare with var is either function-scoped, or global if you’ve declared it outside of a function. Any variable you declare with let is block-scoped, or global if you’ve declared it outside of any other code block.

Again, the Mozilla Dev documentation on let is really rather good and would probably help you understand how it differs from var.

I’ll check it out, but anyway thanks a lot for the help, appreciate it!