0
why does this not work?
I am working on a function that displays the area or the perimeter of any 4 sided shape. but when you try the 2nd case (the one only with a base) it outputs NaN; here is the code: function quadCalculator(isArea, base, height, base2) { if(base2 === undefined){ if (isArea === true) { return base * height; } else { return 2 * (base + height); } } else if (base2 === undefined && height === undefined) { if (isArea === true) { return base ** 2 } else { return base * 4; } } }
3 Answers
+ 1
The issue is that you've placed if-else statements in the wrong order. Parameter order is another issue. Even if you pass this to the function:
rect = quadCalculator(4) //the function accepts this as the isArea parameter, which you have placed first
That's already an issue, because now you don't have a parameter base to be used as well. So after swapping the parameter order, take a look again. The first, not nested if-statement will run if you only input a base because you haven't provided a parameter, base2. And because you haven't defined the parameter isArea, the second, nested else-statement will run, and you don't have a height, either! So you need to swap the order of the outer if-else statements as well. After that, I'm pretty sure it should run.
By the way, if you have program like this to debug, I suggest you type it in the Code Playground and share it with us, as that provides a easier way to debug code.
0
@jianmin chen, your solution worked, but I didn't understand your explanation, please send a link to an article or a video that explains it. Or emphasize your explanation
0
The explanation is in the JS section:
https://code.sololearn.com/WLr3GWaO4E1f/?ref=app