使用更高范围变量和使用在函数中显式传递的变量之间的区别

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

我主要用 JS 编写代码,但我想这适用于许多语言。

函数中的 global/higher 作用域变量与使用传入函数的变量之间的有效区别是什么,反之亦然?

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

如果函数使用范围内的变量可能会导致副作用(函数修改外部变量),这被认为是不好的做法,因为函数 impure.

全局变量被认为是不好的做法,只有在变量为常量时才应使用。如果变量是常量就没问题,因为现在函数不能修改作用域。