Question about function re-assignment

let testVar = 10

function reassign(variable) {
    variable = 100;




In this code, why is it that relative to the function, “testVar” was changed to 100 but relative to the global scope, “testVar” remains unchanged?

Here you are not actually changing testVar with in the function. Even though you are giving it the same value, the parameter, variable, is not the same as the variable, testVar. It is instead its own variable specific to the scope of your function, reassign.

The way the arguments are fed into a function is similar to declaring a variable equal to another variable:

let num_one = 100;
let num_two = num_one;

num_two += 10;

Though num_two has the same value as num_one, and is modified, logging num_one will show it has not changed with num_two.

Several languages, such as C++, let you change a variable in this way by using a pointer. A pointer makes a new variable directly equal to another variable. As such, changing the pointer will change the variable it points to:

#include <iostream>

//       The and symbol,'&', is used to declare a pointer in C++
//             /
void add_to(int &to_change) {
  to_change += 10;
//   \
//    Because to_change is a pointer, the variable it 
//    points to will be changed with it 

int main() {
  int number = 100;

  std::cout << number; // prints 110

However JavaScript does not provide pointers. If you need to change a global variable from a function you have to refer to it directly:

let variable = 100;

const reassign = () => {
  variable += 10;

console.log(variable); // Logs 110
1 Like