Why this f value() cannot access the const num = 3 inside another function though it's being called there but can access the variable below it?
function xyz() {
const num = 3
value() // <-- why this *f value()* cannot access the **num** from here
}
function value() {
console.log(num)
}
const num = 100 // <-- but it can access the **num** here even though it's below of it.
xyz()
the Output is num = 100
I expected the output would be the num = 3.
CodePudding user response:
Let's take a look at your scopes here, you have your main scope with the 2 function declarations and the constant, the scope of value, and the scope of xys. In the value function, the num is the one from the root scope because it is its parent scope. When setting num to 3. You create a new variable that is not the one referenced in the value function. That's why it keeps the one from the root scope
CodePudding user response:
Because JavaScript defines what variables a function can access by where the function is created, not by where it's called. If you want to provide information to a function from where it's called, you do that by passing it arguments instead.
Consider this example:
function handleInputEvents(selector) {
function showChange(value) {
console.log(`Value for "${selector}" changed to "${value}"`);
}
document.querySelector(selector).addEventListener("input", (event) => {
showChange(event.currentTarget.value);
});
}
handleInputEvents(".first");
handleInputEvents(".second");
<div>
<label>
First:
<input type="text" >
</label>
</div>
<div>
<label>
Second:
<input type="text" >
</label>
</div>
In that code, each call to handleInputEvents
creates a new showChange
function. The showChange
function uses two things:
selector
, which it can access because it was created whereselector
is in scope, andvalue
, which it can access becausevalue
is a parameter ofshowChanges
;value
is provided by the caller as an argument
The showChanges
function wouldn't be able to access anything from where it's called (it can't access event
, for instance), but it can access things in scope where it was created.
Related:
CodePudding user response:
Because num = 3 is local variable for xyz().
You need to pass it as a parameter of value() function if you want to access that.
function xyz() {
const num = 3
value(num) // <-- call it with params *num*
function value(num) {
console.log(num)
}
const num = 100
xyz()