Variable scope/function usage

A variable declared outside a function is recognized inside a function without actually passing it as an argument to it. For e.g. the script below runs perfectly.

const y = 3
function operate(x)
    println(x^2+y)
end
operate(5)

Is it recommended to use global variables this way without actually passing them to the function? I would prefer to do something like this instead because of better readability:

const y = 3
function operate(x,z)
    println(x^2+z)
end
operate(5,y)

Which way is more preferred? I understand that for this MWE there is no performance difference, but does the two approaches lead to any significant performance differences for large & complicated functions?

Nope :slightly_smiling_face:.

The very first performance tip recommends against it, and it’s generally considered to be bad style to rely on global variables in any programming language, since they make the flow of information in your code harder to understand.

Independent of performance issues, the manual says:

Passing arguments to functions is better style. It leads to more reusable code and clarifies what the inputs and outputs are.

and I am inclined to agree.

6 Likes

Got it! Thank you :+1: