So, I’m really struggling with React… It’s just a lot different than regular JavaScript.
I’m just messing around and trying to get comfortable with what I’ve learned before moving on and the structure of things in React just really throw me off.
My question is how come I don’t have access to the variable total outside of my sumOfTwo function? Shouldn’t I have access to it within the product function?? I can’t add anything to total because I don’t actually have access to it outside of the sumOfTwo function. I’d rather have {total} in my p tag and not calling the actual function.
export default function Product() {
function sumOfTwo(num1, num2) {
const total = num1 + num2
return total
}
const number = 98
const numberTwo = 50
return (
<div>
<button>click me!</button>
<button>Click to add 1!</button>
<p>{sumOfTwo(number, numberTwo)}</p>
</div>
)
}
I did fix this problem (if this is a proper way of doing it) but I still don’t understand why I wouldn’t have access to total outside of that function because it’s all within one function.
let total
export default function Product() {
function sumOfTwo(num1, num2) {
total = num1 + num2
return total
}
const number = 98
const numberTwo = 50
sumOfTwo(1, 5)
return (
<div>
<button>click me!</button>
<button>Click to add 1!</button>
<p>{total}</p>
</div>
)
}
You declared total inside sumOfTwo, so it is only available inside it.
OK, so initialize a variable named total with the result of calling the sumOfTwo function right before the return statement and use the return value you posted the second time.
FYI - This question/answer is not React specific. This would apply to any JavaScript code written.
As said, that is just plain JS and scopes. If you declare a variable inside a function only that function scope and any inner scope will have access to it. You have to return it out of the function if you want access to it outside the function.
function Product() {
function sumOfTwo(num1, num2) {
const total = num1 + num2;
return total;
}
console.log(sumOfTwo(2, 3)); // 5
console.log(total); // ReferenceError: total is not defined
}
Product();
If you use state variables anything inside the component has access to them and the component will re-render when they change.
This is absolutely not how JavaScript, or basically any other commonly used programming language, works. This isn’t a “React” thing. You have access to variables that are already defined
function example () {
let aVariable = "I'm a string"
function nestedFunction () {
// I can access "aVariable" here
}
}
But you can’t access variables declared in a deeper scope from outside that scope
function example () {
function nestedFunction () {
let aVariable = "I'm a string"
}
// I absolutely cannot access "aVariable" here
}
is this what you were suggesting? I realize my mistake, but I want to make sure this is a proper way of doing this. So now all of the nested functions would have access to total correct? This would also be a real world (generic) example of closures, wouldn’t it?
export default function Function() {
let total
function sumOfTwo(num1, num2) {
total = num1 + num2
return total
}
sumOfTwo(1, 4)
return (
<div>
<button>click me!</button>
<button>Click to add 1!</button>
<p>{total}</p>
</div>
)
}
No, you still do not need declare total without assigning a value to it. Just initialize total with the result of calling sumOfTwo(1, 4).
Also, a function name should describe what it does to make your code more readable. It should never be a generic name.
What is the purpose of your exported function? I really do not understand why you would have a function where you hard code the arguments to get a total.
“Just initialize total with the result of calling sumOfTwo(1, 4)”
this is the part I’m confused on because I can’t access total if it’s created in sumOfTwo()
Also, I was just messing around in react to try and get used to things and made a generic function, I didn’t intend to have to post anything to the forums, but I ran into a problem and decided to post.
closures were something I struggled with, so that is why I wanted to actually figure this out.
export default function Function() {
function sumOfTwo(num1, num2) {
return total = num1 + num2
}
sumOfTwo(1, 4)
return (
<div>
<button>click me!</button>
<button>Click to add 1!</button>
<p>{total}</p>
</div>
)
}
Do the initialization here. Just to be clear, this has nothing to do with React. It is just part of most coding languages. This is not really about closures. It is about variable scope. When a variable is declared inside a function, only the function has access to it
When you originally wrote the above line inside the sumOfTwo function, you could not access total outside. You returned its value, so all you needed to do is use the value returned.
I wasn’t aware you could initialize variables where you would pass arguments to a function. What would this be called? I’d like to do some research on that. I’ve never came across that.
Initializing a variable just means assigning a value to it at the time of declaration. Functions return values, so you can initialize a variable with a call to a function.
Could you possibly give a slight example of what you mean by initializing a variable with a call to a function? I feel like I’m overthinking this.
Do you actually mean initializing a variable in here? sumOfTwo( > initialize in here <) I understand num1 and num2 are initialized when I call the function but how would I do that with total? considering it’s num1 + num2
If you really want to see closure usage, see the examples below. Feel free to ask any questions.
function multiplyBy(factor) {
function product(num) {
return num * factor
}
return product; // returns a function
}
const multiplyBy5 = multiplyBy(5);
console.log(multiplyBy5(10)); // displays 50
const multiplyBy8 = multiplyBy(8);
console.log(multiplyBy8(7)); // displays 56
function counter() {
let count = 0;
function increase() {
count++;
return count;
}
return increase;
}
const myCounter = counter();
console.log(myCounter()); // displays 1
console.log(myCounter()); // displays 2
// The following will call myCounter 10 times
for (let i = 0; i < 10; i++) {
console.log(myCounter());
}
// The last console.log will display 12
Also, you do not have to name the function that is returned. You could just return an anonymous function. So,
function multiplyBy(factor) {
function product(num) {
return num * factor
}
return product; // returns a function
}
could be written as:
function multiplyBy(factor) {
return function(num) {
return num * factor
};
}
and
function counter() {
let count = 0;
function increase() {
count++;
return count;
}
return increase;
}
could be written as:
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}