0

why the arrLength variable doesn't change it's value after the push?

const arr = [1,2,3]

let arrLength = arr.length

arr.push(4)

console.log(arrLength)
  • 2
    Because you set `arrLength` _before_ changing the array's size. After the assignment, `arrLength` and `arr.length` aren't tied together in any way. – 001 Aug 11 '22 at 18:21
  • 1
    Because it's not a reference. It's just a value. [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/q/518000) – VLAZ Aug 11 '22 at 18:22

2 Answers2

0

Integers pass by value, so arrLength is set to equal 3 when arrLength = arr.length is called. It continues to just contain 3 after arr.length is changed because it just contains 3 and isn't dependent on the value of arr.length.

Addison Schmidt
  • 374
  • 1
  • 7
0

It is a matter of reference vs. copy. On line two, the length of the array is copied into the register 'arrLength'. So, even though arr changes later, once the register is accessed, only the outdated copy will be found.

However, if you change line 2 to arr.myLen = () => arr.length; let arrLength = arr.myLen. Now, if line 4 becomes console.log(arrLength()), it will show 4 instead of 3.

Will Sherwood
  • 1,484
  • 3
  • 14
  • 27