skip to Main Content

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


  1. 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

        function calculateSum(a, b, c) {
               return a + b + c;
         }
        let result = calculateSum(5, 10, 5);
        console.log(result);

    If you want c to be dynamic, you may assign default value to c in function definition like this

        function calculateSum(a, b, c = 0) {
               return a + b + c;
         }
        let result = calculateSum(5, 10);
        console.log(result);
    Login or Signup to reply.
  2. 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

    function calculateSum(a, b, c) {  
        return a + b + c;  
    }  
    
    let dynamicC = 3; // You can set this based on your conditions  
    let result = calculateSum(5, 10, dynamicC);  
    console.log(result);

    second is you can declare c inside the function

    function calculateSum(a, b) {  
        let c; // Declare c  
        // Set c based on any conditions you have  
        
        return a + b + c;  
    }  
    
    let result = calculateSum(5, 10);  
    console.log(result); // Output will depend on the condition

    the third one is you can put c variable as a global variable

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search