I started studying Java Script, and I’m having a problem with my code ( from an exercise). And I have no idea how to solve the problem

Asked

Viewed 49 times

-1

function val(x, y, z) {
    if (x !== undefined && y === undefined && z === undefined) {
        return x;
    } else if(x !== undefined && y !== undefined) {
        return x + y;
    } else if(x === undefined && y === undefined && z === undefined) {
        return false;
    } else {
        return (x + y) / z;  // aqui ele não retorna o valor certo
    }                       
}

2 answers

1

The problem is because your code is entering the following condition:

else if(x !== undefined && y !== undefined)

That’s because the two checks of if are satisfied for it to run, to resolve this incident you can include a third check in this if, similar to the one under the above conditions, where the third value is verified (in this case z) is equal to undefined

else if(x !== undefined && y !== undefined && z === undefined)

1

Not answering your problem directly...

You don’t know where to go because you can’t isolate which part of your code is the problem.

First: I strongly recommend you study how to use a Debugger (debugger). This tool will help you isolate problems from your code. I will give you a more general view, from here you can research more specifically:

  • if your code is running on the server (Node.js), check how to configure your text editor (probably VS Code) to run this code in debugger mode;
  • if you are running the code in a browser (in an HTML page), search how to use the Developer Tools Debugger (F12).

Continuing:

Knowing how to use a debugger, you can advance the execution of your code line by line by checking the value of all variables, and then isolate a line that is not giving the result you expected.

For example, imagine that you were waiting for the cursor to enter within an IF else if(x !== undefined && y !== undefined), but did not enter. You are now closer to the source of the problem. You can copy the condition inside the IF and paste it into the console to confirm, and run more detailed tests.

And mostly, having better isolated the source of the problem, you can better target for solutions on the internet, until your questions in the stack overflow will now be much more detailed and answered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.