educative.io

[Help] Could be a bug. Calculator exercise. One of the 5 tests are always failing. Stuck at "NaN"

I’m unable to pass only one of the five tests. I’m stuck when the input values are (5, 3, $) and the output should be “NaN” however, I’m getting this undesired output value 1.6666666666666667
Shouldn’t $ automatically go to the last else block and accept NaN? Why is it printing this strange value 1.6666666666666667?

I have noticed no matter whatever I assigned to ans in the last else block, the ans output is always showing 1.6666666666666667 I suspect it could be an issue with whatever that’s testing the code in the code editor on the website.

Here is my code:

left_operand = left_operand; // Left operand is assigned here

right_operand = right_operand; // Right operand is assigned here

operator = operator; // This is the String representation of operator

ans = ans; // Assign final answer to ans

// Following is an Array of all possible operators

let all_operators= ['+','-','*','/'];

if(operator === '+') {

    // when operator is '+' then

    ans = left_operand + right_operand;

} else if(operator === '-') {

    // when operator '-' then

    ans = left_operand - right_operand;

} else if(operator === '*') {

    // when operator '*' then

    ans = left_operand * right_operand;

} else if(operator = '/') {

    // when operator '/' then

    ans = left_operand / right_operand;

} else {

    // otherwise NaN

    ans = NaN;

}
console.log(`ans value is ${ans}`);

I checked the solution, I’m unable to figure out why this solution does not work?

Hello @Souvik_Kundu,

Your solution is absolutely correct. There was only one problem and that was in the following line of code:

else if(operator = '/')

Instead of =, it should have been ===. It should be noted that = is an assignment operator and cannot be used for comparison purposes. Hence, for the $ operator, the code flow reaches till the second last else statement and falls inside of it instead of skipping it. 1.6666666666666667 is just a garbage value thrown out for the operation left operand $ right operand.

Hope this helps!

1 Like

Thank you @Muhammad_Raahim_Khan very much. How could I have missed that? Bad silly mistake. Thanks a lot again.