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)
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)
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.
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.