const means: you can't change the initially assigned value.
First, define, what is a value in js. Value can be: Booleans, strings, numbers, objects, functions, and undefined values.
Like: People are calling you with your name, it's not changing. However, you change your clothes. The binding between the people and you is your name. The rest can change. Sorry for the weird example.
So, let me give you some examples:
// boolean
const isItOn = true;
isItOn = false; // error
// number
const counter = 0;
counter++; // error
// string
const name = 'edison';
name = 'tesla'; // error
// objects
const fullname = {
name: 'albert',
lastname: 'einstein'
};
fullname = { // error
name: 'werner',
lastname: 'heisenberg'
};
// NOW LOOK AT THIS:
//
// works because, you didn't change the "value" of fullname
// you changed the value inside of it!
fullname.name = 'hermann';
const increase = aNumber => ++aNumber;
increase = aNumber => aNumber + 1; // error
// NOW LOOK AT THIS:
//
// no error because now you're not changing the value
// which is the decrease function itself. function is a
// value too.
let anotherNumber = 3;
const decrease = () => --anotherNumber;
anotherNumber = 10; // no error
decrease(); // outputs 9
const chaos = undefined;
chaos = 'let there be light' // error
const weird = NaN;
weird = 0 // error
As you can see, unless you're not changing the "first" assigned value to a const, no error. Whenever you try to change the first assigned value to something else, it gets angry, and it gives an error.
So, this is the second thing you might know when using const
. Which is, it should be initialized to a value on its declaration or it will be angry.
const orphan; // error
const rich = 0; // no error