I noticed that the let
and const
are similar and behave the same way, but of course there is a reason to create each of them, can you please explain the difference between them with example
Asked
Active
Viewed 106 times
-2

Dani Mousa
- 93
- 9
-
1They are not similar at all. With `const` you declared a variable with a final value, basically. you cannot assign a new value. – Ele Apr 21 '19 at 14:39
-
Core difference: `let` is variable while `const` is constant – Justinas Apr 21 '19 at 14:40
-
2Did you look up the documentation of both? They are pretty well documented. – Ivar Apr 21 '19 at 14:43
-
Great read https://mathiasbynens.be/notes/es6-const – 1565986223 Apr 21 '19 at 14:50
-
1See this :https://wesbos.com/let-vs-const/ – I_Al-thamary Apr 21 '19 at 15:09
2 Answers
1
when you declare variable with const
you can't change the value,
const name = 'john';
name = 'brad'; // throw error
but when you declare variable with let
you can change it
let name = 'john';
name = 'brad';
console.log(name); // brad

Javad Ebrahimi
- 199
- 3
- 11
0
The similarity between let
and const
is that they both have block scope. It means they are only available in the block they are declared.
Difference between them is that variables declared with let
can be assigned a new value but variables declared with const
cannot be assigned a new value.
let x = 3;
x = 'changed';
const y = 33;
y = 'changed' //throws error.
An important point here is that const
only prevents assignment to a new value not the modification of variables.
const obj = {a:1};
obj.a = 5 //will not throw error
obj.b = 'something' //will not throw error
obj = {x:1} //will throw error
Note: If const
is used to declare a primitive type(string,numbers,symbols,boolean,undefined) it can never be changed.

Maheer Ali
- 35,834
- 5
- 42
- 73
-
"An important point here is that const only prevents assignment to a new value not the modification of variables"....this rule will be only applied for objects and arrays, right? – Dani Mousa Apr 21 '19 at 15:01
-
-
@DaniMousa See http://blog.niftysnippets.org/2011/01/myth-of-arrays.html to make the idea of arrays are object more clear. – Maheer Ali Apr 21 '19 at 15:12
-
sorry but i have a new enquiry, is ```NaN``` included with the primitive types in the rule above? – Dani Mousa Apr 21 '19 at 19:52
-