How is value assigned to a variable in R



I have created a function and in that I have created a variable z.

Next, I have assigned a value of z inside the function and a value outside the function. I was hoping that the value of z which is outside the function will influence the value of variable z but I am getting opposite result

f <- function(x) {
        g <- function(y) {
                y + z
        z <- 4
        x + g(x)


and I am getting 10 when I ran in R but I was thinking that answer would be 16



Answer 10 seems like the right answer. Let us execute things as would be run by your computer:

z gets assigned a value of 10, but immediately after that f is called with parameter x = 3

In function f, you define new function g and re-assign the value of z to be 4. Next you call

x + g(x)

which is equal to

3 + g(3)

which is

3 + 3 + 4

which is 10