Quick solution:
function findNextSquare(sq) {
var rt = Math.sqrt(sq);
return rt % 1 !== 0 ? -1 : (rt + 1)**2;
}
Explanation:
This has nothing to do with asynchronicity.
rt++ in console.log((rt++)**2) causes the rt variable to be incremented. Therefore, rt will be different (one more than it should be) when it gets to the return line.
Note the difference:
rt + 1 is an expression that adds 1 to rt and returns the result — rt stays unchanged
rt++ adds 1 to rt, saves the result back to rt, and returns the old rt
++rt adds 1 to rt, saves the result back to rt, and returns the new rt
Let's see what your original code did with sq = 16, with the console.log not commented out:
function findNextSquare(sq) { // sq = 16
var rt = Math.sqrt(sq); // rt = 4
console.log((rt++) ** 2); // logs 4^2 = 16, rt incremented to 5
return rt % 1 !== 0 ? -1 : (rt++)**2; // returns 5^2 = 25, rt incremented to 6 (unneeded)
}
When you remove console.log, this is the result:
function findNextSquare(sq) { // sq = 16
var rt = Math.sqrt(sq); // rt = 4
return rt % 1 !== 0 ? -1 : (rt++)**2; // returns 4^2 = 16, THEN rt is incremented to 5
}
The solution is to add 1 to rt and then square the new value. We don't actually need to save the new value back to rt:
function findNextSquare(sq) { // sq = 16
var rt = Math.sqrt(sq); // rt = 4
return rt % 1 !== 0 ? -1 : (rt + 1)**2; // returns (4 + 1)^2 = 25
}
If you want a console.log in there, you can have it, just make sure it does not change rt:
function findNextSquare(sq) {
var rt = Math.sqrt(sq);
console.log((rt + 1) ** 2);
return rt % 1 !== 0 ? -1 : (rt + 1) ** 2;
}
rtvalue in console log by doingrt++