Student of The Odin Project Here
https://github.com/TheOdinProject/javascript-exercises/tree/solutions/sumAll
I managed to get the sum part of it work (so it's only the first if statement that is the problem)
They want "ERROR" returned if a non-number is passed as either a or b , or if a or b is a negative number.
I used the code below.
First if statement is evaluating to true even if both a and b are numbers
Their solution was to use !Number.isInteger(a)||!Number.isInteger(b)
Any ideas why the first if statement done as below does not work as intended
If I console.log(a)
it logs number
const sumAll = function(a,b) {
let c =0
if((a||b)<0 || (typeof(a)||typeof(b)) !=Number){
return "ERROR"
}
else if(a<b){
for(let i=a; i<=b; i ){
c = i;
}
return c ;
}else if(a>b){for(let i=b; i<=a; i ){
c = i;
}
return c;
}
};
CodePudding user response:
If you want to individually check for a<0 and b<0, you cannot do (a||b)<0
. Reason: a||b
gets evaluated first and you get the first truthy value out of a and b. So, it becomes a matter of order. If you pass 1,-2
you will get 1
as your result of a||b
and obviously 1<0
return false.
function func(a,b){
console.log(a||b);
console.log((a||b)<0);
}
func(1,-2);
func(-1,2);
func(1,2);
Similar problem with (typeof(a)||typeof(b)) !=Number
. You are supposed to individually check ((typeof(a) != 'number') || (typeof(b) != 'number'))
.
Notice how I have changed Number
to 'number'
. typeof
returns a string as mentioned in comments.
You need to amend your if conditions accordingly.