Variable Scopes

It's more likely about JavaScript more than React but I tagged it anyway, my question is in commented lines.
function App() {
const [fullName, setFullName] = useState({
fName: "",
lName: ""
});

const { fName, lName } = fullName; // I destructed fullName as fName and lName and they are in global scope

function handleChange(e) {
const newValue = e.target.value;
const inputName = e.target.name;

setFullName((prevValue) => {
const { fName: prevFName, lName: prevLName } = prevValue; // And here I destructed prevValue as fName and lName, why it doesn't create conflict with fullName destructing? It does work even if I don't rename the variables
console.log(prevValue);
if (inputName === "fName") {
return {
fName: newValue,
lName: prevLName
};
} else {
return {
fName: prevFName,
lName: newValue
};
}
});
}

return (
<div className="container">
<h1>
Hello {fName} {lName}
</h1>
<form>
<input
onChange={handleChange}
value={fName}
name="fName"
placeholder="First Name"
/>

<input
onChange={handleChange}
value={lName}
name="lName"
placeholder="Last Name"
/>
<button>Submit</button>
</form>
</div>
);
}
function App() {
const [fullName, setFullName] = useState({
fName: "",
lName: ""
});

const { fName, lName } = fullName; // I destructed fullName as fName and lName and they are in global scope

function handleChange(e) {
const newValue = e.target.value;
const inputName = e.target.name;

setFullName((prevValue) => {
const { fName: prevFName, lName: prevLName } = prevValue; // And here I destructed prevValue as fName and lName, why it doesn't create conflict with fullName destructing? It does work even if I don't rename the variables
console.log(prevValue);
if (inputName === "fName") {
return {
fName: newValue,
lName: prevLName
};
} else {
return {
fName: prevFName,
lName: newValue
};
}
});
}

return (
<div className="container">
<h1>
Hello {fName} {lName}
</h1>
<form>
<input
onChange={handleChange}
value={fName}
name="fName"
placeholder="First Name"
/>

<input
onChange={handleChange}
value={lName}
name="lName"
placeholder="Last Name"
/>
<button>Submit</button>
</form>
</div>
);
}
1 Reply
dys 🐙
dys 🐙16mo ago
The inner values will "shadow" the outer values, overriding them if they have the same name. It's not a conflict like redefining variables within the same block.
Want results from more Discord servers?
Add your server