Search code examples
functionscopeglobal-variables

Difference between using higher scope variables and using variables explicitly passed in a function


I mainly code in JS, but I guess this would apply to many languages.

What is the effective difference between a global/higher scope variable in a function versus using a variable passed into the function, and vice versa?

let somevariable = 5 ;

function somefuntion() {
  let scopedvariable = 10;
  return scopedvariable*myvariable
}

somefunction();

// OR

let myvariable = 5 ;

function somefuntion(somevariable ) {
  let scopedvariable = 10;
  return scopedvariable *somevariable
}
somefunction(myvariable);

Solution

  • If a function uses a variable from scope that might cause a side effect(function modifying the outer variable) and this is considered bad practice because makes function impure.

    Global variables considered bad practice and should only be used if variable is constant. If the variable is constant it is okay, because now function can't modify the scope.