Challenge - 5 Problems
Lexical Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested function with lexical scope
What is the output of this R code?
R Programming
x <- 10 f <- function() { x <- 20 g <- function() { x } g() } f()
Attempts:
2 left
💡 Hint
Remember that inner functions use variables from their defining environment unless shadowed.
✗ Incorrect
The inner function g() uses the x defined in f(), which is 20, not the global x which is 10.
❓ Predict Output
intermediate2:00remaining
Value of variable after function call
What is the value of x after running this code?
R Programming
x <- 5 foo <- function() { x <- 10 } foo() x
Attempts:
2 left
💡 Hint
Does the function foo() change the global x or only a local copy?
✗ Incorrect
The assignment inside foo() creates a local x; the global x remains unchanged at 5.
❓ Predict Output
advanced2:00remaining
Output of function modifying global variable with <<-
What is the output of this code?
R Programming
x <- 1 modify <- function() { x <<- 2 } modify() x
Attempts:
2 left
💡 Hint
The <<- operator assigns to a variable in the parent environment.
✗ Incorrect
The <<- operator changes the global x to 2, so the output is 2.
❓ Predict Output
advanced2:00remaining
Error caused by variable scope in nested functions
What error does this code produce?
R Programming
outer <- function() {
inner <- function() {
y
}
inner()
}
outer()Attempts:
2 left
💡 Hint
Is y defined anywhere in the function or global environment?
✗ Incorrect
The variable y is not defined anywhere accessible, so R raises an error.
🧠 Conceptual
expert3:00remaining
How many variables are in the environment after execution?
Consider this code. How many variables are in the environment of function f after it runs?
R Programming
f <- function() {
a <- 1
b <- 2
g <- function() {
c <- 3
a + b + c
}
g()
}Attempts:
2 left
💡 Hint
Variables inside g() exist only during g() execution, not in f()'s environment after g() finishes.
✗ Incorrect
Inside f(), only a and b exist as variables after g() runs; c is local to g() and does not remain in f().