Advertisements
here is what I’ve tried
`
function sumAll(start, end) {
let average = Math.abs(start + end) / 2;
let numberOfTerms = Math.abs(end - start) / 1 + 1;
if (start >= 0 && end >= 0 ) {
return Math.abs(average * numberOfTerms);
} else if(typeof start === 'string' || typeof end === 'string'){
return "ERROR";
}else{
return "ERROR";
}
}
console.log("sumAll(10, '90') =" + sumAll(10, "90")); // I want this to return "ERROR" because "90" is String
console.log("sumAll(10, '90') =" + sumAll(10, "x"));// this works
`
but when I change input to "x" it works just fine. I think I miss something.
feel free to tell me anything, I’m a beginner. I’d love to learn new thing.
>Solution :
In your current implementation, you are checking whether the type of start or end is equal to the string ‘string’. Instead, you should be using the typeof operator to check the type of the variables.
Here is how you can modify your function to check for string input and return "ERROR" in that case:
function sumAll(start, end) {
if (typeof start === 'string' || typeof end === 'string') {
return "ERROR";
}
let average = Math.abs(start + end) / 2;
let numberOfTerms = Math.abs(end - start) / 1 + 1;
if (start >= 0 && end >= 0 ) {
return Math.abs(average * numberOfTerms);
} else {
return "ERROR";
}
}
console.log("sumAll(10, '90') =" + sumAll(10, "90")); // "ERROR"
console.log("sumAll(10, 'x') =" + sumAll(10, "x")); // "ERROR"
With this modification, the function will return "ERROR" when either start or end is a string.