0

In the line I have commented below, does the value of the array that has "element" as a value get overridden by array?

let c = [1, 2];
console.log(`c = ${c}`);
add(c, 3);
console.log(`c = ${c}`);

function add(array, element) {
  array = [element]; // Is this Array that has "element" as a value overridden by array
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 1
    You don't override the array. You change the value that is stored in the local `array` variable. That does not influence the value stored in the global `c` variable. – Jonas Wilms Jul 26 '20 at 13:23
  • 1
    What you're describing is a *pass by reference* semantic, and no, JS doesn't have that. You get a copy of a type that is a *reference type*, so that assigning it doesn't copy the whole array, but no, you're not passing a reference to the original variable, so there's no dereferencing on assignment. –  Jul 26 '20 at 13:28
  • 1
    Javascript is pass by value language. In case of objects, value of a variable is a reference. When you pass array `c` to `add` function, you are passing a value of variable `c` which is a reference to an array and this is assigned to local variable `array` of `add` function. But inside the function, you re-assign `array` variable to another array which holds single element. If you call `push` function on the `array`, you will see the changes in the array defined in global scope but re-assigning will not have any affect on the globally defined array. – Yousaf Jul 26 '20 at 13:28

0 Answers0