I was experimenting around with scope inheritance within functions in Python and JavaScript and I want to fully understand why it runs how it does. Note: I have run the examples below in the lastest versions of node and python3.
Question 1: Why is the function expression in case B able to change the global function f() but case A is unable to?
Question 2: In python, we can implement case A as seen below. Is there a way to implement case B in Python and have it return 1?
JavaScript function definition (Case A):
function f() {
return 0
}
function g() {
console.log(f())
}
function h() {
function f() {
return 1
}
g()
}
h() // returns 0
console.log(f()) // returns 0
JavaScript function expression (Case B):
function f() {
return 0
}
function g() {
console.log(f())
}
function h() {
f = function () {
return 1
};
g()
}
h() // returns 1
console.log(f()) // returns 1
Python function definition (Case A):
def f():
return 0
def g():
print(f())
def h():
def f():
return 1
g()
h() # return 0