-2

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

Dani Mousa
  • 93
  • 9

2 Answers2

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