I’m working on a JavaScript project, and I’ve encountered an issue with an "undefined variable" error. Here is the relevant part of my code:
function calculateSum(a, b) {
return a + b + c;
}
let result = calculateSum(5, 10);
console.log(result);
When I run this code, I get the following error in the console:
Uncaught ReferenceError: c is not defined
at calculateSum (script.js:2)
at script.js:5
I understand that the error is because c is not defined, but I’m not sure how to fix it. Could someone explain what I need to do to resolve this error?
I’ve checked the variable names to make sure there are no typos.
I’ve tried declaring c inside the function, but I need it to be dynamic based on some conditions.
Any help or suggestions would be appreciated. Thanks!
2
Answers
Well, based on the snippet you’ve shared variable c isn’t defined anywhere. Your function takes a and b as an input. However, you are returning a+b+c.
Add c to the function definition and it’ll be fixed. Like below
If you want c to be dynamic, you may assign default value to c in function definition like this
The error you’re encountering, Uncaught ReferenceError: c is not defined, occurs because you’re trying to use the variable c inside the calculateSum function without it being defined.
There are some suggestions please try out them.
first one you can pass the c as a parameter
second is you can declare c inside the function
the third one is you can put c variable as a global variable