0

I came across this interesting concept where const behave differently for number, string, Boolean vs Object, arrays.

const num1 = 10
num1 = 20 //throws error

const arr1 = [1,2,3,4]
arr1.push(5) //works
arr1.pop() //works
arr1[2] = 7 //works

arr1 = [2,3] //throws error

For array & objects it allows change in value but throws error in assignment. Is it mean, there is no advantage of declaring object or array as const, as you can change all values anytime?

If anyone can explain, I would like to know, how, behind the scene, const works?

gavdix
  • 358
  • 1
  • 2
  • 21
  • 1
    [`Object.freeze()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) might be what you're after. `const` is used to prevent reassignment, but can still be useful for objects/arrays – Nick Parsons Jul 30 '21 at 10:41
  • 3
    `const` means that the variable ***cannot be reassigned***. That's it. It doesn't make the value immutable. – VLAZ Jul 30 '21 at 10:41
  • an object(an array is also an object) is really a pointer.. `const` means u can't mess with that pointer, but values inside can be manipulated.. `arr` can be a constant but `arr[0]` won't be – The Bomb Squad Jul 30 '21 at 10:43
  • All primitives are immutable, even when using let or var. `var a = 'hello'; a[0] = 'y'; console.log(a) // 'hello;` – evolutionxbox Jul 30 '21 at 10:43
  • 2
    Also, I don't see why you say `const` works differently. `num1 = 20 //throws error` and `arr1 = [2,3] //throws error` are identical operations. Reassignments. In both cases, they are not allowed. `arr1.push(5) //works` is not a reassignment. – VLAZ Jul 30 '21 at 10:46

1 Answers1

1

The const declaration creates a read-only reference to a value. The value it holds is still immutable. Both array and object are holding some values. Those values and properties can be changed but same variable identifier cannot be reassigned.

Here arr1 is an variable identifier

const arr1 = [1,2,3,4]
arr1.push(5) //works // changing the value
arr1.pop() //works //changing the value
arr1[2] = 7 //works // changing the value

Here arr1 got reassigned so it is throwing an error

 arr1 = [2,3] //throws error // reassigning the same variable
brk
  • 48,835
  • 10
  • 56
  • 78