0

I was watching this video that talks about Reference Vs Value In JavaScript. https://www.youtube.com/watch?v=-hBJz2PPIVE

I was really stuck on his last example here.

let c = [1,2] //0x01
console.log('c = ${c}')
add(c,3)
console.log('c = ${c}')
function add(array,element){
    array = [element]
}

The output is

c = 1,2
c = 1,2

I am trying to understand why that is. Based on my understanding, the add function should allocate [element] to a second address (let's say 0x02), then reassign c to 0x02. Which means that the value of c is now the memory address 0x02, hence c = [3]. What is it that I am not understanding correctly?

Phantom
  • 423
  • 1
  • 5
  • 13
  • 1
    `array` was a reference to the same array as `c` before the assignment, but after the assignment it is a reference to a newly created array. `c` is still a reference to the original array. JavaScript is pass by value. Assigning to a local variable can't change the value of another variable. – Paul Aug 21 '19 at 03:21
  • Reassigning a variable name, by itself, will not have any visible effects outside of the scope in which that variable is defined. `array = [element]` reassigns what the local variable name `array` points to inside the remainder of the `add` function - but the function ends there, so the reassignment does nothing. – CertainPerformance Aug 21 '19 at 03:21
  • When you take over the value as a function parameter, it duplicates the new value so the parameter and real value are different variables. So you can't see the changes. – freedev111 Aug 21 '19 at 03:44

0 Answers0